using Beam.Abstractions;
using Beam.Models;
using Microsoft.Playwright;

namespace Beam.Playwright.Strategies;

internal class WaitingDownloadStrategy : IDownloadStrategy {
    public async Task DownloadToStream(string url, int bufferSize, Stream destinationStream, IProgress<IDownloadReport> progress, IPage page,
        CancellationToken ct) {
        
        var download = await page.WaitForDownloadAsync();
        await using var stream = await download.CreateReadStreamAsync();
        var buffer = new byte[bufferSize];
        var inBuffer = 0;
        var downloaded = 0;
        while ((inBuffer = stream.Read(buffer)) > 0) {
            downloaded += inBuffer;
            progress?.Report(new DownloadReport() {
                BytesDownloaded = downloaded,
                BytesRemaining = stream.Length - downloaded
            });
            await destinationStream.WriteAsync(buffer.AsMemory(0, inBuffer), ct);
        }
    }
}