import 'dart:io';
import 'dart:convert';
import 'package:crypto/crypto.dart';
import 'package:path_provider/path_provider.dart';

import 'file_stream_util.dart';
import 'log/logger.dart';

class FileCacheManager {
  static const String TAG = 'FileCacheManager';
  static final FileCacheManager _instance = FileCacheManager._internal();
  factory FileCacheManager() => _instance;
  FileCacheManager._internal();

  late Directory _cacheDir;
  bool _isInitialized = false;

  /// 获取缓存目录
  Future<Directory> _getCacheDirectory() async {
    if (Platform.isIOS) {
      // iOS 使用应用文档目录
      final appDir = await getApplicationDocumentsDirectory();
      final cacheDir = Directory('${appDir.path}/skip_geo');
      if (!await cacheDir.exists()) {
        await cacheDir.create(recursive: true);
      }
      return cacheDir;
    } else {
      // Android 使用外部存储目录
      final appDir = await getExternalStorageDirectory();
      if (appDir == null) {
        throw Exception('Failed to get external storage directory');
      }
      final cacheDir = Directory('${appDir.path}/skip_geo');
      if (!await cacheDir.exists()) {
        await cacheDir.create(recursive: true);
      }
      return cacheDir;
    }
  }

  /// 初始化缓存管理器
  Future<void> init() async {
    if (_isInitialized) return;

    _cacheDir = await _getCacheDirectory();
    _isInitialized = true;
  }

  /// 获取文件内容，如果本地缓存有效则使用缓存，否则下载
  Future<String> getFileContent({
    required String remoteUrl,
    required String fileName,
    required String expectedMd5,
    required Function(double) onProgress,
  }) async {
    try {
      await init();

      final localFilePath = '${_cacheDir.path}/$fileName';
      log(TAG, 'localFilePath: $localFilePath');
      final localFile = File(localFilePath);

      // 检查本地文件是否存在且MD5匹配
      if (await localFile.exists()) {
        final localContent = await localFile.readAsString();
        final localMd5 = md5.convert(utf8.encode(localContent)).toString();

        if (localMd5 == expectedMd5) {
          return localContent;
        }
      }

      // 下载文件
      final result = await FileStreamUtils.readTextFile(
        path: remoteUrl,
        onProgress: onProgress,
      );

      // 验证下载文件的MD5
      // if (result.md5Hash == expectedMd5) {
      //   // 保存到本地
      // }
      await localFile.writeAsString(result.content);
      return result.content;
    } catch (e) {
      log(TAG, 'FileCacheManager getFileContent error: $e');
      return '';
    }
  }

  /// 清除缓存
  Future<void> clearCache() async {
    try {
      await init();
      if (await _cacheDir.exists()) {
        await _cacheDir.delete(recursive: true);
        await _cacheDir.create();
      }
    } catch (e) {
      log(TAG, 'FileCacheManager clearCache error: $e');
    }
  }

  /// 获取缓存大小
  Future<int> getCacheSize() async {
    try {
      await init();
      if (!await _cacheDir.exists()) return 0;

      int totalSize = 0;
      await for (final file in _cacheDir.list(recursive: true)) {
        if (file is File) {
          totalSize += await file.length();
        }
      }
      return totalSize;
    } catch (e) {
      log(TAG, 'FileCacheManager getCacheSize error: $e');
      return 0;
    }
  }
}
