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

import 'package:image_picker/image_picker.dart';

class FileRepository {
  const FileRepository({required this.baseDirectory});
  final Directory baseDirectory;

  Future<File> persistTemporaryFile(XFile file, String name) async {
    File fileOnDisk = File("${baseDirectory.path}/$name");
    await fileOnDisk.writeAsBytes(await file.readAsBytes());

    return fileOnDisk;
  }

  Future<File> persistTemporaryFileFromBytes(Uint8List bytes, String name) async {
    File fileOnDisk = File("${baseDirectory.path}/$name");
    await fileOnDisk.writeAsBytes(bytes as List<int>);

    return fileOnDisk;
  }

  Future<List<File>> getFilesByPrefix(String prefix) async {
    return await baseDirectory
        .list()
        .where((file) => file is File)
        .map((file) => file as File)
        .where((file) => file.path.split("/").last.startsWith(prefix))
        .toList();
  }

  Future<void> deleteAllFilesByPrefix(String prefix) async {
    for (File file in await getFilesByPrefix(prefix)) {
      await file.delete();
    }
  }
}
