using System.IO;
using System.Windows.Media.Imaging;
using ytLive.Services;

namespace ytLive.Helpers;

public static class ImageCache
{
    private static readonly Dictionary<string, BitmapImage> Cache = new(StringComparer.OrdinalIgnoreCase);

    public static BitmapImage? Get(string assetId)
    {
        if (string.IsNullOrWhiteSpace(assetId)) return null;
        if (Cache.TryGetValue(assetId, out var image)) return image;

        var bytes = LayoutStore.Instance?.GetAssetBytes(assetId);
        if (bytes == null || bytes.Length == 0) return null;

        var bitmap = Decode(bytes);
        if (bitmap != null) Cache[assetId] = bitmap;
        return bitmap;
    }

    public static void Put(string key, BitmapImage image) => Cache[key] = image;

    public static BitmapImage? FromBytes(byte[] bytes)
    {
        try
        {
            using var stream = new MemoryStream(bytes, writable: false);
            var bitmap = new BitmapImage();
            bitmap.BeginInit();
            bitmap.CacheOption = BitmapCacheOption.OnLoad;
            bitmap.StreamSource = stream;
            bitmap.EndInit();
            bitmap.Freeze();
            return bitmap;
        }
        catch
        {
            return null;
        }
    }

    private static BitmapImage? Decode(byte[] bytes) => FromBytes(bytes);
}
