// 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 UnityEditor;
using UnityEngine;
using UnityEngine.UIElements;

namespace WPFMA
{
    internal static class WPFMAControlPanelTheme
    {
        private const string PanelTypeName = "VRCSdkControlPanel";
        private const string BannerPath = "Assets/WPFMA-SDK/IMG/label_uploading.png";
        private const string WindowTitle = "WPFMA Build Panel";
        private const float MinimumHeight = 620f;
        private const string StylePath = "Assets/WPFMA-SDK/UI/WPFMAControlPanel.uss";
        private const string EnabledKeyPrefix = "WPFMA.Panel.Theme.";

        private static StyleSheet sheet;

        internal static bool Enabled
        {
            get { return EditorPrefs.GetBool(EnabledKeyPrefix + ProjectKey(), true); }
            set
            {
                EditorPrefs.SetBool(EnabledKeyPrefix + ProjectKey(), value);

                if (value)
                    Apply();
                else
                    Strip();
            }
        }

        [InitializeOnLoadMethod]
        private static void Hook()
        {
            EditorApplication.update -= Tick;
            EditorApplication.update += Tick;
        }

        private static double nextTick;

        private static void Tick()
        {
            // The clock first: it's free, Enabled reads EditorPrefs.
            if (EditorApplication.timeSinceStartup < nextTick || !Enabled)
                return;

            nextTick = EditorApplication.timeSinceStartup + 0.5;

            var panel = Find();
            if (panel != null)
                ApplyStyles(panel);
        }

        [MenuItem("WPFMA-SDK/Show Control Panel", false, 600)]
        internal static void ShowControlPanel()
        {
            if (!EditorApplication.ExecuteMenuItem("VRChat SDK/Show Control Panel"))
            {
                EditorUtility.DisplayDialog("VRChat SDK not found",
                    "Install the VRChat Base SDK package before opening the build panel.", "OK");
                return;
            }

            Schedule(3);
        }

        internal static void Schedule(int passes)
        {
            if (passes <= 0)
                return;

            EditorApplication.delayCall += () =>
            {
                Apply();
                Schedule(passes - 1);
            };
        }

        internal static void Apply()
        {
            var panel = Find();
            if (panel == null)
                return;

            try
            {
                if (panel.titleContent == null || panel.titleContent.text != WindowTitle)
                    panel.titleContent = new GUIContent(WindowTitle);

                if (panel.minSize.y < MinimumHeight)
                    panel.minSize = new Vector2(panel.minSize.x, MinimumHeight);

                var position = panel.position;
                if (position.height < MinimumHeight)
                {
                    position.height = MinimumHeight;
                    panel.position = position;
                }

                ApplyBanner(panel);
                ApplyStyles(panel);
                panel.Repaint();
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not restyle the VRChat control panel: " + e.Message);
            }
        }

        private static void ApplyStyles(EditorWindow panel)
        {
            if (!Enabled)
                return;

            var root = panel.rootVisualElement;
            if (root == null)
                return;

            if (sheet == null)
                sheet = AssetDatabase.LoadAssetAtPath<StyleSheet>(StylePath);

            if (sheet == null)
                return;

            Attach(root);

            var builder = root.Q("builder-panel");
            if (builder != null)
                Attach(builder);
        }

        private static void Attach(VisualElement element)
        {
            int count = element.styleSheets.count;

            if (count > 0 && element.styleSheets[count - 1] == sheet)
                return;

            element.styleSheets.Remove(sheet);
            element.styleSheets.Add(sheet);
        }

        private static void Strip()
        {
            var panel = Find();
            if (panel == null || panel.rootVisualElement == null || sheet == null)
                return;

            panel.rootVisualElement.styleSheets.Remove(sheet);

            var builder = panel.rootVisualElement.Q("builder-panel");
            if (builder != null)
                builder.styleSheets.Remove(sheet);

            panel.Repaint();
        }

        private static string projectKey;

        // The project's folder doesn't change while Unity runs, so it's worked out once.
        private static string ProjectKey()
        {
            if (projectKey != null)
                return projectKey;
            unchecked
            {
                uint hash = 2166136261;
                foreach (var c in Application.dataPath.ToLowerInvariant())
                {
                    hash ^= c;
                    hash *= 16777619;
                }

                return projectKey = hash.ToString("x8");
            }
        }

        private static void ApplyBanner(EditorWindow panel)
        {
            var root = panel.rootVisualElement;
            if (root == null)
                return;

            var banner = root.Q("banner");
            if (banner == null)
                return;

            var image = AssetDatabase.LoadAssetAtPath<Texture2D>(BannerPath);
            if (image == null)
                return;

            banner.style.backgroundImage = image;
        }

        private static EditorWindow Find()
        {
            foreach (var window in Resources.FindObjectsOfTypeAll<EditorWindow>())
            {
                if (window != null && window.GetType().Name == PanelTypeName)
                    return window;
            }

            return null;
        }
    }
}
#endif
