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

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

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

  void getData() {
    historyList.clear();
    historyList.addAll(HistoryData().getWallpaperData().reversed.toList());
    _refreshList();
  }

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


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

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