import 'package:get/get.dart';
import 'package:trans_lark/entity/history_model.dart';
import 'package:trans_lark/global/flutter_tts_manager.dart';
import 'package:trans_lark/hive/history_data.dart';
import 'package:trans_lark/router/get_router.dart';
import 'package:trans_lark/util/t_object_utils.dart';

class TranslatorRecordController extends GetxController {
  RxMap<String, List<HistoryEntity>> historyList = <String, List<HistoryEntity>>{}.obs;

  @override
  void onInit() {
    super.onInit();
    historyList.value = HistoryData().getMapList();
  }

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

  void onTextToSpeech(HistoryEntity entity, {String? text}) {
    if (TObjectUtils.isNotEmpty(entity.targetText)) {
      FlutterTtsManager().translatorTtsPlay(
        entity.targetText!,
        entity.targetLanguageCode!,
      );
    }
  }

  void deleteHistoryItem(String key, HistoryEntity entity, int index) {
    final list = HistoryData().getAllHistory();
    historyList.forEach((key, value) {
      value.removeWhere((e) => e.translationTime == entity.translationTime);
    });
    if (historyList[key] != null && historyList[key]!.isEmpty) {
      historyList.remove(key);
    }
    final deleteEntity = list.firstWhereOrNull(
        (item) => item.translationTime == entity.translationTime);
    if (deleteEntity != null) {
      HistoryData().deleteHistory(list.indexOf(deleteEntity));
    }
  }
}
