import 'package:flutter_translate/manager/tts.dart';
import 'package:flutter_translate/model/language_model.dart';
import 'package:flutter_translate/model/scene_model.dart';
import 'package:flutter_translate/pages/home/home_controller.dart';
import 'package:flutter_translate/pages/scene_list/components/language_selector.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';

class SceneListController extends GetxController {
  final HomeController homeController = Get.put(HomeController());

  late Rx<LanguageModel> fromLanguage = Rx<LanguageModel>(
    homeController.fromLanguage.value.clone(),
  );
  late Rx<LanguageModel> toLanguage = Rx<LanguageModel>(
    homeController.toLanguage.value.clone(),
  );

  var sceneList = <SceneList>[];
  RxBool isPlayingFrom = false.obs;
  RxBool isPlayingTo = false.obs;
  RxInt playIndex = 0.obs;

  @override
  void onInit() {
    super.onInit();
    sceneList = Get.arguments;
  }

  void showChangeLanguageBottomSheet(bool isFrom) {
    if (isFrom) {
      Get.bottomSheet(
        LanguageSelector(isFrom: isFrom),
      );
    } else {
      Get.bottomSheet(
        LanguageSelector(isFrom: isFrom),
      );
    }
  }

  void playTranslationResults(
    bool isFrom,
    SceneList item,
    int playIndex,
  ) async {
    this.playIndex.value = playIndex;
    isPlayingTo.value = false;
    isPlayingFrom.value = false;
    if (isFrom) {
      isPlayingFrom.value = true;
      await Tts().voiceTranslator(
        getSentence(isFrom, item),
        fromLanguage.value.code,
      );
      isPlayingFrom.value = false;
    } else {
      isPlayingTo.value = true;
      await Tts().voiceTranslator(
        getSentence(isFrom, item),
        toLanguage.value.code,
      );
      isPlayingTo.value = false;
    }
  }

  String getSentence(bool isFrom, SceneList sceneList) {
    List keys = sceneList.toMap().keys.toList();
    List values = sceneList.toMap().values.toList();
    int index = keys.indexWhere(
        (e) => e == (isFrom ? fromLanguage.value.name : toLanguage.value.name));
    if (index != -1) return values[index];
    return 'loading';
  }

  void changeLanguage(LanguageModel item, bool isFrom) {
    if (isFrom) {
      fromLanguage.update((fn) {
        fn?.code = item.code;
        fn?.name = item.name;
      });
    } else {
      toLanguage.update((fn) {
        fn?.code = item.code;
        fn?.name = item.name;
      });
    }
    Get.back();
  }

  void languageConvert() {
    var code = toLanguage.value.code;
    var name = toLanguage.value.name;

    toLanguage.update((fn) {
      fn?.code = fromLanguage.value.code;
      fn?.name = fromLanguage.value.name;
    });
    fromLanguage.update((fn) {
      fn?.code = code;
      fn?.name = name;
    });
  }
}
