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

import 'package:path_provider/path_provider.dart';

import 'ConnectFileStorage.dart';

class FileStorage implements ConnectFileStorage {
  static const String proofFolder = "proof";

  @override
  Future<String> proofDirectory() async {
    final Directory base = await getApplicationDocumentsDirectory();
    final Directory folder = Directory("${base.path}/$proofFolder");

    if (!await folder.exists()) {
      await folder.create(recursive: true);
    }

    return folder.path;
  }

  @override
  Future<String> saveProof(String name, Uint8List bytes) async {
    final String folder = await proofDirectory();
    final File file = File("$folder/$name");
    await file.writeAsBytes(bytes);
    return file.path;
  }

  @override
  Future<Uint8List?> readProof(String reference) async {
    final File file = File(reference);

    if (!await file.exists()) {
      return null;
    }

    return await file.readAsBytes();
  }

  @override
  Future<bool> deleteProof(String reference) async {
    final File file = File(reference);

    if (!await file.exists()) {
      return false;
    }

    await file.delete();
    return true;
  }
}
