import 'package:flutter_tts/flutter_tts.dart';
import 'package:trans_lark/util/log_print.dart';
import 'package:trans_lark/widget/base_easyloading.dart';

class FlutterTtsManager {
  FlutterTtsManager._();

  static final FlutterTtsManager _instance = FlutterTtsManager._();

  factory FlutterTtsManager() {
    return _instance;
  }

  late FlutterTts ttsController;

  Future<void> init() async {
    LogPrint.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);
    LogPrint.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) {
      BaseEasyLoading.toast('This language cannot be played');
      return;
    }
  }
}
