import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get/get_rx/get_rx.dart';
import 'package:wallpaperx/common/components/dialog/remind_dialog.dart';
import 'package:wallpaperx/common/components/view_state_widget.dart';
import 'package:wallpaperx/common/storage/favorite_data.dart';
import 'package:wallpaperx/routes/app_pages.dart';

class FavoriteController extends GetxController {
  static FavoriteController get to => Get.find<FavoriteController>();
  late ScrollController scrollController;
  late ViewState viewState;
  RxList favoriteList = [].obs;

  @override
  void onInit() {
    super.onInit();
    scrollController = ScrollController();
    getData();
  }

  @override
  void onClose() {
    scrollController.dispose();
    super.onClose();
  }

  void getData() {
    favoriteList.clear();
    favoriteList.addAll(FavoriteData().getWallpaperData().reversed.toList());
    _refreshList();
  }

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

  /// 点击壁纸
  void onTapItem(int index) {
    Get.toNamed(AppPages.wallpaperDet, arguments: {
      'position': index,
      'wallpaperList': favoriteList,
    });
  }

  /// 长按壁纸
  void onLongPress(int index) {
    Get.dialog(
      barrierDismissible: false,
      RemindDialog(
        content: 'Are you sure you want to delete the wallpaper?',
        confirmOnTap: () {
          // 计算原始列表中的对应索引
          int indexToRemoveFromDb =
              FavoriteData().getWallpaperData().length - 1 - index;
          FavoriteData().delete(indexToRemoveFromDb);
          favoriteList.removeAt(index);
          _refreshList();
        },
      ),
    );
  }

  /// 删除所有壁纸
  void deleteAll() {
    Get.dialog(
      barrierDismissible: false,
      RemindDialog(
        content: 'Are you sure to delete all wallpapers?',
        confirmOnTap: () async {
          FavoriteData().clear();
          favoriteList.clear();
          _refreshList();
        },
      ),
    );
  }
}
