using SkiaSharp;
using View_by_Distance.Shared.Models.Methods;

namespace View_by_Distance.ThumbHash.Models;

public class C2_ThumbHasher : IThumbHasher
{

    private static SKBitmap GetBitmap(string path)
    {
        SKBitmap result;
        using SKBitmap skBitmap = SKBitmap.Decode(path);
        result = skBitmap.Copy(SKColorType.Rgba8888);
        return result;
    }

    private static byte[] Encode(SKBitmap skBitmap) =>
        ThumbHash.RgbaToThumbHash(skBitmap.Width, skBitmap.Height, skBitmap.GetPixelSpan());

    private static byte[] Encode(string path)
    {
        byte[] results;
        using SKBitmap skBitmap = GetBitmap(path);
        results = Encode(skBitmap);
        return results;
    }

    byte[] IThumbHasher.Encode(string path) =>
        Encode(path);

    private static MemoryStream GetMemoryStream(byte[] thumbHashBytes, int width, int height)
    {
        MemoryStream result = new();
        (int w, int h) = (width / 2, height / 2);
        using SKManagedWStream skManagedWStream = new(result);
        byte[] bytes = ThumbHash.ThumbHashToRgba(thumbHashBytes, w, h);
        SKImageInfo skImageInfo = new(w, h, SKColorType.Rgba8888, SKAlphaType.Unpremul);
        using SKImage skImage = SKImage.FromPixelCopy(skImageInfo, bytes);
        using SKData sdData = skImage.Encode(SKEncodedImageFormat.Png, 100);
        sdData.SaveTo(result);
        return result;
    }

    MemoryStream IThumbHasher.GetMemoryStream(byte[] thumbHashBytes, int width, int height) =>
        GetMemoryStream(thumbHashBytes, width, height);

    (byte[], MemoryStream) IThumbHasher.EncodeAndSave(string path, int width, int height)
    {
        byte[] results;
        MemoryStream result;
        using SKBitmap skBitmap = GetBitmap(path);
        results = Encode(skBitmap);
        result = GetMemoryStream(results, width, height);
        return (results, result);
    }

}