// Author: fengshengxiong
// Date: 2024/5/8
// Description: 收藏播放列表盒子

import 'package:get/get.dart';
import 'package:hive/hive.dart';
import 'package:tone_snap/data/models/playlist_model.dart';
import 'package:tone_snap/data/storage/hive_storage.dart';

class CollectPlaylistsBox {
  CollectPlaylistsBox._();

  static final CollectPlaylistsBox _instance = CollectPlaylistsBox._();

  factory CollectPlaylistsBox() {
    return _instance;
  }

  /// 声明盒子
  /// 注意, main函数中这个盒子已经打开, 可以进行存储操作
  final _box = Hive.box<PlaylistModel>(collectPlaylistsBox);

  /// 获取列表
  List<PlaylistModel> getList() {
    return _box.values.toList();
  }

  /// 获取倒序列表
  List<PlaylistModel> getReversedList() {
    return _box.values.toList().reversed.toList();
  }

  /// 添加数据
  Future<int> add({required String id, required String title, String? params, String? coverUrl, String? subtitle}) async {
    return await _box.add(PlaylistModel(
      id: id,
      title: title,
      params: params,
      coverUrl: coverUrl,
      subtitle: subtitle,
    ));
  }

  /// 删除
  Future<void> delete(String id) async {
    var list = getList();
    var model = list.firstWhereOrNull((e) => e.id == id);
    if (model != null) {
      await _box.deleteAt(list.indexOf(model));
      await _box.flush();
    }
  }

  /// 清空所有数据
  Future<void> clear() async {
    await _box.clear();
    await _box.flush();
  }
}
