using System;
using System.Text.Json;
using LiteDB;

namespace Dacryptero.Data
{
    public class FileEntry
    {
        [BsonId]
        public ObjectId Id { get; set; } = new ObjectId();
        
        public DateTime Date { get; set; }

        public string Path { get; set; } = "";

        [BsonIgnore]
        public ReadOnlyMemory<byte> StorageKey { get; set; }

        public string StorageKeyString
        {
            get => Convert.ToBase64String(StorageKey.Span);
            set => StorageKey = Convert.FromBase64String(value);
        }

        [BsonIgnore]
        public ReadOnlyMemory<byte> StorageIV { get; set; }

        public string StorageIVString
        {
            get => Convert.ToBase64String(StorageIV.Span);
            set => StorageIV = Convert.FromBase64String(value);
        }
        
        [BsonIgnore]
        public ReadOnlyMemory<byte> StorageHash { get; set; }

        public string StorageHashString
        {
            get => Convert.ToBase64String(StorageHash.Span);
            set => StorageHash = Convert.FromBase64String(value);
        }
    
        public void WriteTo(Utf8JsonWriter writer, DB.DBConfig config)
        {
            writer.WriteStartObject();
            writer.WriteString("date", Date);
            writer.WriteBase64String("hash", StorageHash.Span);
            writer.WriteBoolean("exists", System.IO.File.Exists(
                System.IO.Path.Combine(config.DirectoryPath, Path)
            ));
            writer.WriteEndObject();
        }
    }
}