using HMUI;
using IllusionPlugin;
using SimpleJSON;
using System;
using UnityEngine;


namespace SongBrowserPlugin.UI
{
    class Base64Sprites
    {
        // https://www.iconfinder.com/icons/17236/folder_icon
        public static string Folder = "[encoded data, 21280 characters]";
        
        public static Sprite Base64ToSprite(string base64)
        {
            if (base64.StartsWith("data:image/png;base64,"))
            {
                base64 = base64.Remove(0, "data:image/png;base64,".Length);
            }

            Sprite s = null;
            try
            {
                Texture2D tex = Base64ToTexture2D(base64);
                s = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), (Vector2.one / 2f));
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception loading texture from base64 data.");
                s = null;
            }

            return s;
        }

        public static Texture2D Base64ToTexture2D(string encodedData)
        {
            byte[] imageData = Convert.FromBase64String(encodedData);

            int width, height;
            GetImageSize(imageData, out width, out height);

            Texture2D texture = new Texture2D(width, height, TextureFormat.ARGB32, false, true);
            texture.hideFlags = HideFlags.HideAndDontSave;
            texture.filterMode = FilterMode.Trilinear;
            texture.LoadImage(imageData);
            return texture;
        }

        private static void GetImageSize(byte[] imageData, out int width, out int height)
        {
            width = ReadInt(imageData, 3 + 15);
            height = ReadInt(imageData, 3 + 15 + 2 + 2);
        }

        private static int ReadInt(byte[] imageData, int offset)
        {
            return (imageData[offset] << 8) | imageData[offset + 1];
        }
    }
}
