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/page/translator_history/translator_history_state.dart';
import 'package:trans_lark/router/router.dart';
import 'package:trans_lark/storage/history_data.dart';
import 'package:trans_lark/util/obj_util.dart';

class TranslatorHistoryLogic extends GetxController {
  final state = TranslatorHistoryState();

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

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

  void translatorTtsPlay(HistoryEntity entity) {
    if (ObjUtil.isNotEmpty(entity.targetText)) {
      FlutterTtsManager().translatorTtsPlay(
        entity.targetText!,
        entity.targetLanguageCode!,
      );
    }
  }

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