import 'package:SEFER/constant/box_name.dart';
import 'package:SEFER/main.dart';
import 'package:flutter/material.dart';
import 'package:flutter_tts/flutter_tts.dart';
import 'package:get/get.dart';

class TextToSpeechController extends GetxController {
  final flutterTts = FlutterTts();

  // Initialize TTS in initState
  @override
  void onInit() {
    super.onInit();
    initTts();
  }

  // Dispose of TTS when controller is closed
  @override
  void onClose() {
    super.onClose();
    flutterTts.completionHandler;
  }

  // Function to initialize TTS engine
  Future<void> initTts() async {
    String? lang =
        WidgetsBinding.instance.platformDispatcher.locale.countryCode;
    await flutterTts.setLanguage(box.read(BoxName.lang)); //'en-US' Set language
    // await flutterTts.setLanguage('ar-SA'); //'en-US' Set language
    // await flutterTts.setLanguage(lang!); //'en-US' Set language
    await flutterTts.setSpeechRate(0.5); // Adjust speech rate
    await flutterTts.setVolume(1.0); // Set volume
  }

  // Function to speak the given text
  Future<void> speakText(String text) async {
    try {
      await flutterTts.awaitSpeakCompletion(true);
      var result = await flutterTts.speak(text);
      if (result == 1) {
        // TTS operation has started
        // You can perform additional operations here, if needed
      }
    } catch (error) {
      // Handle error gracefully, e.g., show a message
      Get.snackbar('Error', 'Failed to speak text: $error');
      print('Failed to speak text: $error');
    }
  }
}
