using CliWrap;

namespace InnovEnergy.Lib.Channels.V2.Pipes;

public class AsyncPipeSource : PipeSource
{
    private readonly Func<Task<IReadOnlyList<Byte>>> _Read;
    private Byte[]? _Buffer;

    public AsyncPipeSource(Func<Task<IReadOnlyList<Byte>>> read)
    {
        _Read = read;
    }

    public override async Task CopyToAsync(Stream destination, CancellationToken cancellationToken = new CancellationToken())
    {
        var rx = await _Read();

        if (rx is Byte[] ba)
        {
            await destination.WriteAsync(ba, 0, ba.Length, cancellationToken);
            return;
        }
        
        if (_Buffer is null || _Buffer.Length < rx.Count )
        {
            _Buffer = rx.ToArray();
        }
        else
        {
            var i = 0;
            foreach (var b in rx)
                _Buffer[i++] = b;
        }
        
        await destination.WriteAsync(_Buffer, 0, rx.Count, cancellationToken);

    }
}