namespace EEMSServerCore.Hubs;

internal partial class ClientsMainHub
{
    private readonly ConcurrentDictionary<Guid, MemoryStream> _streamBuffer = [];
    public readonly ConcurrentDictionary<Guid, string> _savePath = [];
    public Task<bool> FilePack(Guid guid, byte[] buffer, int current, int total)
    {
        Debug.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);
        string path = Path.Combine(Environment.CurrentDirectory, "Receive");
        if (!Compressor.DecompressZipFile(new(path), 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();
    }
}