// WPFMA-SDK needs Unity 2022.3 (VRChat's version); on older Unity this file is skipped and WPFMAUnityVersionNotice explains why.
#if UNITY_2022_3_OR_NEWER
using System;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

namespace WPFMA
{
    /// <summary>
    /// The panel's color theme. WPFMA-SDK is designed in blue; a theme moves every blue tone (backgrounds, accents,
    /// text, and the blue parts of the banner art) to another color, so the whole panel changes together. Status
    /// colors (green OK, amber warning, red error) are left alone so they keep their meaning.
    /// </summary>
    internal static class WPFMATheme
    {
        internal sealed class Option
        {
            public string Name;
            public float Hue;          // target hue in degrees
            public bool Mono;          // no color at all
            public Color Swatch;
        }

        private const string PrefKey = "WPFMA.Theme";

        // The blue the panel is designed around, and how far from it a tone still counts as "blue".
        private const float BaseHue = 207f;
        private const float CoreRange = 40f;
        private const float FadeRange = 22f;

        internal static readonly Option[] Options =
        {
            new Option { Name = "Blue", Hue = BaseHue, Swatch = new Color(126f / 255f, 182f / 255f, 222f / 255f) },
            new Option { Name = "Red", Hue = 355f, Swatch = new Color(0.90f, 0.42f, 0.45f) },
            new Option { Name = "Orange", Hue = 24f, Swatch = new Color(0.95f, 0.62f, 0.38f) },
            new Option { Name = "Gold", Hue = 45f, Swatch = new Color(0.93f, 0.78f, 0.38f) },
            new Option { Name = "Green", Hue = 135f, Swatch = new Color(0.45f, 0.85f, 0.52f) },
            new Option { Name = "Teal", Hue = 172f, Swatch = new Color(0.40f, 0.83f, 0.78f) },
            new Option { Name = "Purple", Hue = 268f, Swatch = new Color(0.68f, 0.52f, 0.95f) },
            new Option { Name = "Pink", Hue = 322f, Swatch = new Color(0.95f, 0.50f, 0.80f) },
            new Option { Name = "Mono", Mono = true, Swatch = new Color(0.78f, 0.78f, 0.78f) }
        };

        private static Option current;
        private static readonly Dictionary<Color, Color> shifted = new Dictionary<Color, Color>();
        private static readonly Dictionary<string, Texture2D> banners = new Dictionary<string, Texture2D>();

        /// <summary>Goes up every time the theme changes, so windows know to rebuild their cached styles.</summary>
        internal static int Version { get; private set; }

        internal static event Action Changed;

        internal static Option Current
        {
            get
            {
                if (current == null)
                {
                    string name = EditorPrefs.GetString(PrefKey, "Blue");
                    current = Array.Find(Options, o => o.Name == name) ?? Options[0];
                }
                return current;
            }
            set
            {
                if (value == null || value == Current)
                    return;
                current = value;
                EditorPrefs.SetString(PrefKey, value.Name);
                shifted.Clear();
                foreach (var texture in banners.Values)
                    if (texture != null)
                        UnityEngine.Object.DestroyImmediate(texture);
                banners.Clear();
                Version++;
                if (Changed != null)
                    Changed();
                UnityEditorInternal.InternalEditorUtility.RepaintAllViews();
            }
        }

        private static bool IsDefault
        {
            get { return !Current.Mono && Mathf.Approximately(Current.Hue, BaseHue); }
        }

        /// <summary>A panel color in the current theme (blue tones move to the theme's color; others stay).</summary>
        internal static Color Shift(Color color)
        {
            if (IsDefault)
                return color;
            Color result;
            if (shifted.TryGetValue(color, out result))
                return result;
            result = ShiftPixel(color, Current);
            shifted[color] = result;
            return result;
        }

        private static Color ShiftPixel(Color color, Option theme)
        {
            float h, s, v;
            Color.RGBToHSV(color, out h, out s, out v);
            if (s < 0.02f)
                return color;
            float weight = BlueWeight(h * 360f);
            if (weight <= 0f)
                return color;

            Color target;
            if (theme.Mono)
            {
                target = Color.HSVToRGB(h, 0f, v);
            }
            else
            {
                // Keep how far from the base blue it was, so the art's shading survives.
                float hue = Mathf.Repeat(theme.Hue + (h * 360f - BaseHue), 360f) / 360f;
                target = Color.HSVToRGB(hue, s, v);
            }
            target.a = color.a;
            return weight >= 1f ? target : Color.Lerp(color, target, weight);
        }

        /// <summary>1 for clearly blue hues, fading to 0 outside the blue range.</summary>
        private static float BlueWeight(float hueDegrees)
        {
            float distance = Mathf.Abs(Mathf.DeltaAngle(hueDegrees, BaseHue));
            if (distance <= CoreRange)
                return 1f;
            if (distance >= CoreRange + FadeRange)
                return 0f;
            return 1f - (distance - CoreRange) / FadeRange;
        }

        /// <summary>A banner image in the current theme (recolored once, then kept in Library so switching is instant).</summary>
        internal static Texture2D Banner(string path)
        {
            var source = AssetDatabase.LoadAssetAtPath<Texture2D>(path);
            if (source == null || IsDefault)
                return source;

            Texture2D themed;
            if (banners.TryGetValue(path, out themed) && themed != null)
                return themed;

            themed = LoadCached(path) ?? Recolor(source, path);
            banners[path] = themed;
            return themed ?? source;
        }

        private static string CachePath(string path)
        {
            long stamp = File.Exists(path) ? File.GetLastWriteTimeUtc(path).Ticks : 0;
            return Path.Combine("Library", "WPFMATheme", Current.Name + "-" + Path.GetFileNameWithoutExtension(path) + "-" + stamp + ".png");
        }

        private static Texture2D LoadCached(string path)
        {
            try
            {
                string cache = CachePath(path);
                if (!File.Exists(cache))
                    return null;
                var texture = new Texture2D(2, 2, TextureFormat.RGBA32, false) { hideFlags = HideFlags.HideAndDontSave };
                if (texture.LoadImage(File.ReadAllBytes(cache)))
                    return texture;
                UnityEngine.Object.DestroyImmediate(texture);
            }
            catch (Exception)
            {
            }
            return null;
        }

        private static Texture2D Recolor(Texture2D source, string path)
        {
            var previous = RenderTexture.active;
            var temporary = RenderTexture.GetTemporary(source.width, source.height, 0, RenderTextureFormat.ARGB32, RenderTextureReadWrite.sRGB);
            try
            {
                // Works whatever the import settings are (not readable, compressed...).
                Graphics.Blit(source, temporary);
                RenderTexture.active = temporary;
                var texture = new Texture2D(source.width, source.height, TextureFormat.RGBA32, false) { hideFlags = HideFlags.HideAndDontSave };
                texture.ReadPixels(new Rect(0, 0, source.width, source.height), 0, 0);

                var pixels = texture.GetPixels32();
                var theme = Current;
                var memo = new Dictionary<int, Color32>();
                for (int i = 0; i < pixels.Length; i++)
                {
                    var p = pixels[i];
                    int key = (p.r << 16) | (p.g << 8) | p.b;
                    Color32 result;
                    if (!memo.TryGetValue(key, out result))
                    {
                        result = ShiftPixel(p, theme);
                        if (memo.Count < 200000)
                            memo[key] = result;
                    }
                    result.a = p.a;
                    pixels[i] = result;
                }
                texture.SetPixels32(pixels);
                texture.Apply(false, false);

                try
                {
                    string cache = CachePath(path);
                    Directory.CreateDirectory(Path.GetDirectoryName(cache));
                    File.WriteAllBytes(cache, texture.EncodeToPNG());
                }
                catch (Exception)
                {
                }
                return texture;
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not recolor " + path + " for the theme: " + e.Message);
                return null;
            }
            finally
            {
                RenderTexture.active = previous;
                RenderTexture.ReleaseTemporary(temporary);
            }
        }
    }
}
#endif
