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

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

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

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

  void getHistoryList() {
    historyList.clear();
    historyList.addAll(HistoryData().getWallpaperData().reversed.toList());
    refreshHistoryList();
  }

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

  /// 点击壁纸
  void toImageDetail(int position) {
    Get.toNamed(AppPages.wallpaperDetail, arguments: {
      'position': position,
      'isSetHistory': false,
      'wallpaperList': historyList,
    });
  }

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