import 'package:flutter_tts/flutter_tts.dart';
import 'package:trans_lark/util/t_print.dart';
import 'package:trans_lark/widget/t_base_easy_loading.dart';

class FlutterTtsManager {
  FlutterTtsManager._();

  factory FlutterTtsManager() {
    return _instance;
  }

  static final FlutterTtsManager _instance = FlutterTtsManager._();

  late FlutterTts ttsController;

  Future<void> init() async {
    TPrint.d("TTS Service init start");
    ttsController = FlutterTts();
    await ttsController.setSharedInstance(true);
    await ttsController.setIosAudioCategory(
        IosTextToSpeechAudioCategory.ambient,
        [
          IosTextToSpeechAudioCategoryOptions.allowBluetooth,
          IosTextToSpeechAudioCategoryOptions.allowBluetoothA2DP,
          IosTextToSpeechAudioCategoryOptions.mixWithOthers
        ],
        IosTextToSpeechAudioMode.voicePrompt);
    await ttsController.awaitSpeakCompletion(true);
    await ttsController.awaitSynthCompletion(true);
    TPrint.d("TTS Service init success");
  }

  Future<void> translatorTtsPlay(String text, String language) async {
    try {
      await ttsController.stop();
      await ttsController.setLanguage(language);
      await ttsController.speak(text);
    } catch (e) {
      TBaseEasyLoading.toast('This language cannot be played');
      return;
    }
  }
}
