// Author: fengshengxiong
// Date: 2024/5/8
// Description: 下载歌曲盒子

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

class OfflineBox {
  OfflineBox._();

  static final OfflineBox _instance = OfflineBox._();

  factory OfflineBox() {
    return _instance;
  }

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

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

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

  /// 添加数据
  Future<int> add(MusicModel model) async {
    return await _box.add(model);
  }

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

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

  /// 获取第一条的封面
  String? getFirstCoverUrl() {
    if (getReversedList().isNotEmpty) {
      return getReversedList().first.coverUrl;
    }
    return null;
  }

  /// 校验是否已下载
  bool checkDownloaded(String? videoId) {
    var model = getList().firstWhereOrNull((e) => e.videoId == videoId);
    return model != null;
  }
}
