import 'dart:developer';
import 'dart:io';
import 'dart:math' as math;
import 'package:path_provider/path_provider.dart';

class CacheTool {
  /// 获取临时目录大小
  static Future<int> getCacheSize() async {
    Directory tempDir = await getApplicationCacheDirectory();
    return await _getTotalSizeOfFilesInDir(tempDir);
  }

  /// 递归计算文件夹大小
  static Future<int> _getTotalSizeOfFilesInDir(FileSystemEntity file) async {
    if (file is File) {
      return await file.length();
    }
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      int total = 0;
      for (final child in children) {
        total += await _getTotalSizeOfFilesInDir(child);
      }
      return total;
    }
    return 0;
  }

  /// 将字节转换为可读单位
  static String formatBytes(int bytes, {int decimals = 2}) {
    if (bytes <= 0) return "0 B";
    const suffixes = ["B", "KB", "MB", "GB", "TB"];
    var i = (math.log(bytes) / math.log(1024)).floor();
    return ((bytes / math.pow(1024, i)).toStringAsFixed(decimals)) + ' ' + suffixes[i];
  }

  /// 清理缓存
  static Future<void> clearCache() async {
    Directory tempDir = await getApplicationCacheDirectory();
    await _deleteDir(tempDir);
  }

  static Future<void> _deleteDir(FileSystemEntity file) async {
    if (file is Directory) {
      final List<FileSystemEntity> children = file.listSync();
      for (final child in children) {
        await _deleteDir(child);
      }
    }
    await file.delete();
  }
}
