using System.Windows;

namespace EEMSServerCore.Hubs;

internal partial class ClientsMainHub
{
    private static readonly ConcurrentDictionary<Guid, MemoryStream> _streamBuffer = [];
    public static readonly ConcurrentDictionary<Guid, string> _savePath = [];
    public Task<bool> FilePack(Guid guid, byte[] buffer, int current, int total)
    {
        Console.WriteLine($"FilePack {guid} {current} {total}");
        if (!_streamBuffer.TryGetValue(guid, out MemoryStream? stream) || stream is null)
        {
            if (current != 1)
                return Task.FromResult(false);

            stream = new();
            _streamBuffer[guid] = stream;
            Timer timer = new(FileCleanerTimerCallback, guid, 600000, Timeout.Infinite);
        }

        stream.Write(buffer);

        if (current != total)
            return Task.FromResult(true);

        if (!Compressor.DecompressZipFile(Environment.CurrentDirectory, stream))
            return Task.FromResult(false);

        if (_streamBuffer.TryRemove(guid, out MemoryStream? memoryStream) && memoryStream is not null)
            memoryStream.Dispose();

        MessageBox.Show("File Received");
        return Task.FromResult(true);
    }

    private void FileCleanerTimerCallback(object? state)
    {
        if (state is not Guid guid)
            return;

        if (_streamBuffer.TryRemove(guid, out MemoryStream? memoryStream) && memoryStream is not null)
            memoryStream.Dispose();
    }
}
