using System.Diagnostics;
using Universal;

namespace EEMSClientCore;

public class ClientProvider(IClientCaller clientCaller, IClientBaseProvider baseProvider) : IClientProvider
{
    public Task<bool> RequestFile(Guid guid, FileType fileType)
    {
        Debug.WriteLine($"RequestFile {guid} {fileType}");

        string? filePath = fileType switch
        {
            FileType.Config => baseProvider.ConfigPath,
            FileType.Recipe => baseProvider.RecipePath,
            _ => default
        };

        if (string.IsNullOrEmpty(filePath))
            return Task.FromResult(false);

        if (!Directory.Exists(filePath))
            return Task.FromResult(false);
        
        using MemoryStream stream = new();
        Compressor.CompressZipFileDirectory(new(filePath), stream);

        return SendFile(guid, stream);
    }

    private async Task<bool> SendFile(Guid guid, MemoryStream stream)
    {
        if (!stream.Split(out List<byte[]>? buffer, 8192) || buffer is null)
            return false;

        for (int i = 0; i < buffer.Count; i++)
        {
            try
            {
                if (!await clientCaller.FilePack(guid, buffer[i], i + 1, buffer.Count))
                    return false;
            }
            catch
            {
                return false;
            }
        }
        return true;
    }
}

public interface IClientBaseProvider
{
    public string? RecipePath { get; set; }
    public string? ConfigPath { get; set; }
}  