import 'package:get/get.dart';
import 'package:speech_to_text/speech_recognition_error.dart';
import 'package:speech_to_text/speech_to_text.dart';
import 'package:trans_lark/util/log_print.dart';
import 'package:trans_lark/widget/base_easyloading.dart';

class SpeechToTextManager {
  static final SpeechToTextManager _instance = SpeechToTextManager._();

  factory SpeechToTextManager() {
    return _instance;
  }

  SpeechToTextManager._();

  final _speechToText = SpeechToText();
  var hasSpeech = false;
  var isListening = false.obs;

  Future<void> initSpeech() async {
    try {
      BaseEasyLoading.loading();
      hasSpeech = await _speechToText.initialize(
        onStatus: _statusListener,
        onError: _errorListener,
      );
      BaseEasyLoading.dismiss();
      _speechToText.statusListener ??= _statusListener;
      _speechToText.errorListener ??= _errorListener;
    } catch (e) {
      LogPrint.d('Speech recognition failed: ${e.toString()}');
    }
  }

  void _statusListener(String status) {
    LogPrint.d('状态：$status');
    if (status == 'listening') {
      isListening.value = true;
    } else {
      isListening.value = false;
    }
  }

  void _errorListener(SpeechRecognitionError error) {
    LogPrint.d('Received error status: $error, listening: ${_speechToText.isListening}');
    BaseEasyLoading.toast('Speech recognition failed: ${error.errorMsg}');
  }

  Future<void> startListening(String localeId, SpeechResultListener onResult) async {
    BaseEasyLoading.loading();
    try {
      await _speechToText.listen(
        onResult: onResult,
        localeId: localeId,
        listenFor: const Duration(minutes: 30),
        pauseFor: const Duration(minutes: 3),
        listenOptions: SpeechListenOptions(
          cancelOnError: true,
          autoPunctuation: true,
          listenMode: ListenMode.dictation,
        ),
      );
      BaseEasyLoading.dismiss();
    } catch (e) {
      if (e.runtimeType == ListenFailedException) {
        LogPrint.d('speechToText.listen：${(e as ListenFailedException).message}');
      } else {
        LogPrint.d('speechToText.listen：${e.toString()}');
      }
      BaseEasyLoading.toast('The current language does not support speech recognition');
    }
  }

  Future<void> stopListening() async {
    if (isListening.value) {
      BaseEasyLoading.loading();
      await _speechToText.stop();
      BaseEasyLoading.dismiss();
    }
  }
}
