using Avalonia.Media;
using Avalonia.Media.Imaging;
using SkiaSharp;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InABox.Avalonia;

public static class ImageUtils
{
    public static Bitmap? ImageFromBytes(byte[]? value, bool transparent = true)
    {
        Bitmap? result = null;
        if (value?.Any() == true)
        {
            if (transparent)
            {
                var skb = SKBitmap.Decode(value);
                var transparentColor = skb.GetPixel(0, 0);
                var newPixels = skb.Pixels.Select(x => Equals(x, transparentColor) ? SKColors.Transparent : x);
                skb.Pixels = newPixels.ToArray();
                SKImage image = SKImage.FromPixels(skb.PeekPixels());
                SKData encoded = image.Encode(SKEncodedImageFormat.Png, 100);
                value = encoded.ToArray();
            }
            
            using (var stream = new MemoryStream(value))
            {
                result = new Bitmap(stream);
            }
        }

        return result;
    }
}
