import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:tone_snap/components/base_easyloading.dart';
import 'package:tone_snap/components/dialog/remind_dialog.dart';
import 'package:tone_snap/components/dialog/rename_dialog.dart';
import 'package:tone_snap/components/view_state_widget.dart';
import 'package:tone_snap/data/models/voice_model.dart';
import 'package:tone_snap/data/storage/favorite_box.dart';
import 'package:tone_snap/modules/sidea/initial/initial_controller.dart';
import 'package:tone_snap/routes/app_routes.dart';

class FavouriteController extends GetxController {
  static FavouriteController get to => Get.find<FavouriteController>();
  var scrollController = ScrollController();
  var voiceList = <VoiceModel>[].obs;
  var viewState = ViewState.loading.obs;

  @override
  void onReady() {
    super.onReady();
    getData();
  }

  void getData() {
    voiceList.value = FavoriteBox().getList().reversed.toList();
    _refreshList();
  }

  void _refreshList() {
    viewState.value = voiceList.isNotEmpty ? ViewState.normal : ViewState.empty;
    voiceList.refresh();
  }

  void onTapItem(VoiceModel item) {
    InitialController.to.currentPlayVoiceModel.value = item;
    Get.toNamed(AppRoutes.playSound, arguments: item);
  }

  void onTapReName(VoiceModel item) {
    Get.dialog(
      barrierDismissible: true,
      RenameDialog(
        name: item.name,
        confirmOnTap: (value) {
          item.name = value;
          item.save();
          voiceList.refresh();

          // 若 item 和当前正播放的 item 是同个对象，则需要同步修改
          if (item.path == InitialController.to.currentPlayVoiceModel.value?.path) {
            InitialController.to.currentPlayVoiceModel.update((e) => e?.name = value);
          }
        },
      ),
    );
  }

  void onTapDelete(VoiceModel item) {
    Get.dialog(
      RemindDialog(
        content: 'Are you sure to delete it?',
        confirmOnTap: () async {
          BaseEasyLoading.loading();
          await item.delete();
          voiceList.remove(item);
          BaseEasyLoading.toast('Removed');

          // 若 item 和当前正播放的 item 是同个对象，则需要同步修改
          if (item.path == InitialController.to.currentPlayVoiceModel.value?.path) {
            InitialController.to.isFavourite.value = false;
          }
          _refreshList();
        },
      ),
    );
  }
}
