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/my_voice_box.dart';
import 'package:tone_snap/modules/sidea/initial/initial_controller.dart';
import 'package:tone_snap/routes/app_routes.dart';

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

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

  void getData() {
    voiceList.value = MyVoiceBox().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 (identical(item, InitialController.to.currentPlayVoiceModel.value)) {
            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');
          _refreshList();
        },
      ),
    );
  }
}
