import 'dart:io';

import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:speech_to_text/speech_recognition_result.dart';
import 'package:trans_lark/entity/history_model.dart';
import 'package:trans_lark/global/speech_to_text_manager.dart';
import 'package:trans_lark/global/translate_manager.dart';
import 'package:trans_lark/router/router.dart';
import 'package:trans_lark/storage/history_data.dart';
import 'package:trans_lark/util/log_print.dart';
import 'package:trans_lark/util/obj_util.dart';
import 'package:trans_lark/util/permission_util.dart';
import 'package:trans_lark/widget/base_easyloading.dart';
import 'package:trans_lark/widget/speak_dialog.dart';

import 'translator_state.dart';

/// @description:
/// @author
/// @date: 2024-06-27 13:55:27
class TranslatorLogic extends GetxController {
  final state = TranslatorState();

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

  @override
  void onClose() {
    state.textController.dispose();
    super.onClose();
  }

  initData() async {
    state.historyList.value = HistoryData().getList().reversed.toList();
  }

  void onTapSuffix() {
    if (state.isValue.value) {
      state.textController.text = "";
      state.isValue.value = false;
    } else {
      _onTapSpeak();
    }
  }

  Future<void> _onTapSpeak() async {
    bool micResult =
        await PermissionUtil.checkPermission([Permission.microphone]);
    if (!micResult) return;
    if (Platform.isIOS) {
      bool speechResult =
          await PermissionUtil.checkPermission([Permission.speech]);
      if (!speechResult) return;
    }
    await Get.dialog(
      barrierDismissible: true,
      useSafeArea: false,
      SpeakDialog(
        isListening: SpeechToTextManager().isListening,
        onTap: () async {
          if (!SpeechToTextManager().hasSpeech) {
            await SpeechToTextManager().initSpeech();
          }
          if (SpeechToTextManager().hasSpeech) {
            if (SpeechToTextManager().isListening.value) {
              _openTranslatorResultPage();
            } else {
              SpeechToTextManager().startListening(
                  TranslateManager().fromLanguageEntity.value.languageCode,
                  _onSpeechResult);
            }
          } else {
            Get.back();
            BaseEasyLoading.toast('Speech not available');
          }
        },
      ),
    );
    if (Get.isDialogOpen != null && !Get.isDialogOpen!) {
      SpeechToTextManager().stopListening();
    }
  }

  void _onSpeechResult(SpeechRecognitionResult result) {
    LogPrint.d('识别结果：${result.recognizedWords}');
    state.lastWords = result.recognizedWords;
  }

  void _openTranslatorResultPage() {
    if (ObjUtil.isEmpty(state.lastWords)) {
      BaseEasyLoading.toast('No text recognized');
      return;
    }
    Get.back();
    Get.toNamed(
      GetRouter.translateResult,
      arguments: {"sourceText": state.lastWords},
    );
  }

  void onTapHistoryItem(HistoryEntity entity) {
    Get.toNamed(
      GetRouter.translateResult,
      arguments: {
        'sourceText': entity.sourceText,
        'targetText': entity.targetText,
        'isHistory': true,
        'fromLanguage': entity.sourceLanguageName,
        'toLanguage': entity.targetLanguageName,
      },
    );
  }

  void deleteItem(int index) {
    // 计算原始列表中的对应索引
    int indexToRemoveFromDb = HistoryData().getList().length - 1 - index;
    state.historyList.removeAt(indexToRemoveFromDb);
    HistoryData().delete(indexToRemoveFromDb);
  }

  void onChanged(String value) {
    state.isValue.value = value.trim().isNotEmpty;
  }

  void onSubmitted(String value) {
    Get.toNamed(
      GetRouter.translateResult,
      arguments: {"sourceText": value},
    );
  }

  void insertHistory(HistoryEntity entity) {
    state.historyList.insert(0, entity);
  }

  void cleanAllHistory() {
    state.historyList.clear();
    HistoryData().clear();
  }
}
