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

import '../../main.dart';

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

  @override
  void onInit() {
    super.onInit();
    initTts();
  }

  @override
  void onClose() {
    flutterTts.stop(); // Stop any ongoing TTS
    super.onClose();
  }

  // Initialize TTS engine with language check
  Future<void> initTts() async {
    try {
      String langCode = box.read(BoxName.lang) ?? 'en-US';
      bool isAvailable = await flutterTts.isLanguageAvailable(langCode);

      // If language is unavailable, default to 'en-US'
      if (!isAvailable) {
        langCode = 'en-US';
      }

      await flutterTts.setLanguage(langCode);
      await flutterTts.setSpeechRate(0.5); // Adjust speech rate
      await flutterTts.setVolume(1.0); // Set volume
    } catch (error) {
      Get.snackbar('Error', 'Failed to initialize TTS: $error');
    }
  }

  // Function to speak the given text
  Future<void> speakText(String text) async {
    try {
      await flutterTts.awaitSpeakCompletion(true);
      await flutterTts.speak(text);
    } catch (error) {
      Get.snackbar('Error', 'Failed to speak text: $error');
    }
  }
}
