using System.Globalization;
using Avalonia;
using Avalonia.Data.Converters;
using Avalonia.Media;
using Avalonia.Media.Imaging;
using Avalonia.Platform;
using SkiaSharp;

namespace InABox.Avalonia.Converters;

public class ByteArrayToImageSourceConverter : AbstractConverter<byte[]?, IImage?>
{
    
    public bool Transparent { get; set; } = false;
    
    protected override IImage? Convert(byte[]? value, object? parameter = null)
    {
        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;
    }
}