import 'package:flutter_translate/common/hive/history_data.dart';
import 'package:flutter_translate/common/utils/object_utils.dart';
import 'package:flutter_translate/manager/tts.dart';
import 'package:flutter_translate/model/history_model.dart';
import 'package:flutter_translate/pages/home/home_controller.dart';
import 'package:flutter_translate/router/get_gages.dart';
import 'package:get/get.dart';

class HistoryController extends GetxController {
  RxMap<String, List<HistoryModel>> historyMap =
      <String, List<HistoryModel>>{}.obs;
  RxBool isPlaying = false.obs;
  RxInt playTranslationTime = 0.obs;
  HomeController homeController = Get.find<HomeController>();

  @override
  void onInit() {
    super.onInit();
    historyMap.value = HistoryData().findGroup();
  }

  void historyTranslate(HistoryModel historyModel) {
    Get.toNamed(
      GetPages.translateText,
      arguments: {
        'isHistory': true,
        'sourceText': historyModel.sourceText,
        'targetText': historyModel.targetText,
        'fromLanguageName': historyModel.sourceLanguageName,
        'toLanguageName': historyModel.targetLanguageName,
        'fromLanguageCode': historyModel.sourceLanguageCode,
        'toLanguageCode': historyModel.targetLanguageCode,
      },
    );
  }

  void voiceTranslator(HistoryModel entity) async {
    isPlaying.value = false;
    playTranslationTime.value = entity.translationTime ?? 0;
    if (ObjectUtils.isNotEmpty(entity.targetText)) {
      isPlaying.value = true;
      await Tts().voiceTranslator(
        entity.targetText!,
        entity.targetLanguageCode!,
      );
      isPlaying.value = false;
    }
  }

  void remove(String key, HistoryModel entity) {
    final list = HistoryData().findAll();
    historyMap.forEach((key, value) {
      value.removeWhere((e) => e.translationTime == entity.translationTime);
    });
    if (historyMap[key] != null && historyMap[key]!.isEmpty) {
      historyMap.remove(key);
    }
    final deleteEntity = list.firstWhereOrNull(
        (item) => item.translationTime == entity.translationTime);
    if (deleteEntity != null) {
      HistoryData().remove(list.indexOf(deleteEntity));
    }
  }
}
