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";
    final fileToSave = File(filePath);

    _checkAndCreateDir(storagePath);

    if (!await fileToSave.exists()) await fileToSave.create();
    await fileToSave.writeAsBytes(file.toList());
    return true;
  }

  Future<void> _checkAndCreateDir(String dir) async {
    final directory = Directory(dir);
    final parentDirectory = directory.parent;
    if (!await parentDirectory.exists()) await parentDirectory.create();
    if (!await directory.exists()) await directory.create();
  }

  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;
  }
}
