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 CollectionController extends GetxController {
  static CollectionController get to => Get.find<CollectionController>();
  late ScrollController scrollController;
  late ViewState viewState;
  RxList favoriteList = [].obs;

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

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

  void getFavoriteList({String? dataType}) {
    favoriteList.clear();
    favoriteList.addAll(FavoriteData().getWallpaperData().reversed.toList());
    _refreshFavoriteList(type: 0);
  }

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

  /// 点击壁纸
  void toImageDetail(int position, {List? images}) {
    Get.toNamed(AppPages.wallpaperDetail, arguments: {
      'position': position,
      'wallpaperList': favoriteList,
    });
  }

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