using SkiaSharp;

namespace NodePipeline.Application;

public static class ImageSaver
{
    public static void Save(in ImageBuffer buffer, string path)
    {
        using var bitmap = new SKBitmap(buffer.Width, buffer.Height,
            SKColorType.Rgba8888, SKAlphaType.Premul);

        var span = buffer.GetPixelSpan();
        var idx = 0;

        for (var y = 0; y < buffer.Height; y++)
        for (var x = 0; x < buffer.Width; x++)
        {
            var r = span[idx++];
            var g = span[idx++];
            var b = span[idx++];
            var a = span[idx++];
            bitmap.SetPixel(x, y, new SKColor(r, g, b, a));
        }

        using var image = SKImage.FromBitmap(bitmap);
        using var data = image.Encode(SKEncodedImageFormat.Png, 100);
        using var stream = File.OpenWrite(path);
        data.SaveTo(stream);
    }
}