import 'dart:io';
import 'dart:typed_data';

import 'package:path_provider/path_provider.dart';

/// 文件存储
class FileStorage {
  FileStorage({
    required this.directory,
  });

  /// 存储目录
  final String directory;

  Future<Uint8List?> read(String fileName) async {
    final storagePath = await _getStoragePath();
    final filePath = "$storagePath/$fileName";
    final file = File(filePath);
    if (!await file.exists()) return null;
    final text = await file.readAsBytes();
    return text;
  }

  Future<bool> save(String fileName, Uint8List file) async {
    final storagePath = await _getStoragePath();
    final filePath = "$storagePath/$fileName";
    File fileToSave = File(filePath);

    _checkAndCreateDir(storagePath);

    if (!await fileToSave.exists()) {
      try {
        fileToSave = await fileToSave.create(recursive: true);
      } catch (e) {
        print(e);
      }
    }
    await fileToSave.writeAsBytes(file.toList());
    return true;
  }

  Future<bool> delete(String fileName) async {
    final storagePath = await _getStoragePath();
    final filePath = "$storagePath/$fileName";
    final file = File(filePath);

    if (await file.exists()) {
      try {
        await file.delete();
        return true;
      } catch (e) {
        print(e);
        return false;
      }
    }

    return false;
  }

  Future<bool> deleteDirectory(String directoryPath) async {
    final storagePath = await _getStoragePath();
    final directory = Directory(storagePath);
    final result = await directory.exists();
    if (result) {
      try {
        await directory.delete(recursive: true);
        return true;
      } catch (e) {
        print(e);
        return false;
      }
    }

    return false;
  }

  Future<void> _checkAndCreateDir(String dir) async {
    final directory = Directory(dir);
    final parentDirectory = directory.parent;
    try {
      if (!await parentDirectory.exists()) {
        await parentDirectory.create(recursive: true);
      }
    } catch (e) {
      print(e);
    }
    if (!await directory.exists()) {
      try {
        await directory.create();
      } catch (e) {
        print(e);
      }
    }
  }

  Future<String> _getStoragePath() async {
    Directory? dir;
    if (Platform.isAndroid) {
      dir = await getExternalStorageDirectory();
    }
    dir ??= await getApplicationDocumentsDirectory();
    if (directory.isNotEmpty) {
      return "${dir.path}/$directory";
    }
    return dir.path;
  }
}
