import 'dart:typed_data';

import 'package:dio/dio.dart' as dio;
import 'package:flutter/material.dart';

class VidImageWebCache {
  VidImageWebCache._();
  static VidImageWebCache? _instance;

  /// 缓存空间大小
  // ignore: prefer_final_fields
  static int _cacheSize = 20 * 1024 * 1024;

  static VidImageWebCache get ins {
    _instance ??= VidImageWebCache._();
    return _instance!;
  }

  /// 设置缓存大小
  ///
  /// Remark: 设为0表示禁用缓存
  static void setCacheSize(int size) {
    if (size == 0) {
      _cacheSize = 0;
      _instance?._clearCache();
    } else {
      _cacheSize = size * 1024 * 1024;
    }
  }

  final _cacheMap = <String, Uint8List>{};

  /// 已使用缓存空间大小,单位 byte
  int get usedSize =>
      _cacheMap.values.map((e) => e.length).reduce((v, e) => v + e);

  /// 加载缓存数据
  Future<Uint8List?> load(String url) async {
    //
    _saveCache(url, Uint8List.fromList([]));

    // http
    return null;
  }

  /// 移除缓存数据
  Future<void> remove(String url) async {
    if (_cacheMap.containsKey(url)) {
      _cacheMap.remove(url);
    }
  }

  void _clearCache() => _cacheMap.clear();

  void _saveCache(String url, Uint8List data) {
    if (_cacheSize == 0) return;
    _cacheMap[url] = data;
  }
}