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

namespace WPFMA
{
    internal static class WPFMAHierarchyIcons
    {
        private const string EnabledKeyPrefix = "WPFMA.Hierarchy.Enabled.";

        private const string SettingsTypeName = "qtools.qhierarchy.pdata.QSettings";
        private const string SettingTypeName = "qtools.qhierarchy.pdata.QSetting";

        private const string ShowIcons = "ComponentsShow";
        private const string ShowInPlayMode = "ComponentsShowDuringPlayMode";
        private const string IconSize = "ComponentsIconSize";
        private const string ShowActive = "VisibilityShow";
        private const string ShowActiveInPlayMode = "VisibilityShowDuringPlayMode";
        private const string ShowRenderer = "RendererShow";
        private const string ShowRendererInPlayMode = "RendererShowDuringPlayMode";
        private const string Order = "ComponentsOrder";
        private const string EyeBesideScripts = "0;2;3;4;5;6;7;8;9;10;11;12;1";
        private const string ActiveColor = "AdditionalActiveColor";
        private const string InactiveColor = "AdditionalInactiveColor";

        private static Type settingsType;
        private static Type settingType;
        private static bool resolved;

        internal static bool Available
        {
            get { return Resolve(); }
        }

        internal static bool ComponentIcons
        {
            get { return GetBool(ShowIcons); }
            set { SetBool(ShowIcons, value); }
        }

        internal static bool ShowDuringPlayMode
        {
            get { return GetBool(ShowInPlayMode); }
            set { SetBool(ShowInPlayMode, value); }
        }

        internal static bool LargeIcons
        {
            get { return GetInt(IconSize) >= 1; }
            set { SetInt(IconSize, value ? 1 : 0); }
        }

        internal static bool ObjectToggle
        {
            get { return GetBool(ShowActive); }
            set
            {
                SetBool(ShowActive, value);
                SetBool(ShowActiveInPlayMode, value);
            }
        }

        internal static bool MeshToggle
        {
            get { return GetBool(ShowRenderer); }
            set
            {
                SetBool(ShowRenderer, value);
                SetBool(ShowRendererInPlayMode, value);
            }
        }

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

                if (value)
                    Apply();
                else
                    Debug.Log("[WPFMA-SDK] Hierarchy toggles left to QHierarchy's own settings from now on.");
            }
        }

        internal static void ApplyIfEnabled()
        {
            if (!Resolve() || !Enabled)
                return;

            if (ComponentIcons && ObjectToggle && MeshToggle && ShowDuringPlayMode)
                return;

            Apply();
        }

        internal static void Apply()
        {
            if (!Resolve())
            {
                Debug.LogWarning("[WPFMA-SDK] QHierarchy is not loaded, so the hierarchy toggles cannot be set.");
                return;
            }

            ComponentIcons = true;
            ShowDuringPlayMode = true;
            ObjectToggle = true;
            MeshToggle = true;
            MakeIconsVisible();

            Set(Order, EyeBesideScripts);

            Debug.Log("[WPFMA-SDK] Hierarchy toggles on. " + Status());
        }

        internal static string Status()
        {
            if (!Resolve())
                return "QHierarchy is not loaded.";

            return "eye=" + OnOff(ShowActive) +
                   ", mesh=" + OnOff(ShowRenderer) +
                   ", components=" + OnOff(ShowIcons) +
                   ", in play mode=" + OnOff(ShowInPlayMode) +
                   ", order=" + Get("ComponentsOrder", "?");
        }

        private static string OnOff(string name)
        {
            return GetBool(name) ? "on" : "OFF";
        }

        internal static void MakeIconsVisible()
        {
            if (!Resolve())
                return;

            if (EditorGUIUtility.isProSkin)
            {
                SetColor(ActiveColor, new Color(0.80f, 0.80f, 0.80f, 0.72f));
                SetColor(InactiveColor, new Color(0.42f, 0.42f, 0.42f, 0.65f));
            }
            else
            {
                SetColor(ActiveColor, new Color(0.18f, 0.18f, 0.18f, 0.70f));
                SetColor(InactiveColor, new Color(0.45f, 0.45f, 0.45f, 0.60f));
            }

            EditorApplication.RepaintHierarchyWindow();
        }

        private static void SetColor(string name, Color value)
        {
            try
            {
                var instance = Instance();
                var setting = SettingValue(name);
                if (instance == null || setting == null)
                    return;

                var method = settingsType.GetMethod("setColor", BindingFlags.Public | BindingFlags.Instance);
                if (method != null)
                    method.Invoke(instance, new object[] { setting, value });
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not recolour the hierarchy icons: " + e.Message);
            }
        }

        private static bool Resolve()
        {
            if (resolved)
                return settingsType != null && settingType != null;

            resolved = true;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    if (settingsType == null)
                        settingsType = assembly.GetType(SettingsTypeName, false);

                    if (settingType == null)
                        settingType = assembly.GetType(SettingTypeName, false);

                    if (settingsType != null && settingType != null)
                        break;
                }
                catch (Exception)
                {
                }
            }

            return settingsType != null && settingType != null;
        }

        private static object Instance()
        {
            var getter = settingsType.GetMethod("getInstance", BindingFlags.Public | BindingFlags.Static);
            return getter != null ? getter.Invoke(null, null) : null;
        }

        private static object SettingValue(string name)
        {
            return Enum.IsDefined(settingType, name) ? Enum.Parse(settingType, name) : null;
        }

        private static T Get<T>(string name, T fallback)
        {
            if (!Resolve())
                return fallback;

            try
            {
                var instance = Instance();
                var setting = SettingValue(name);
                if (instance == null || setting == null)
                    return fallback;

                var method = settingsType.GetMethod("get", BindingFlags.Public | BindingFlags.Instance);
                if (method == null)
                    return fallback;

                return (T)method.MakeGenericMethod(typeof(T)).Invoke(instance, new[] { setting });
            }
            catch (Exception)
            {
                return fallback;
            }
        }

        private static void Set<T>(string name, T value)
        {
            if (!Resolve())
                return;

            try
            {
                var instance = Instance();
                var setting = SettingValue(name);
                if (instance == null || setting == null)
                    return;

                foreach (var method in settingsType.GetMethods(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (method.Name != "set" || !method.IsGenericMethodDefinition)
                        continue;

                    var parameters = method.GetParameters();
                    if (parameters.Length != 3)
                        continue;

                    method.MakeGenericMethod(typeof(T)).Invoke(instance, new object[] { setting, value, true });
                    EditorApplication.RepaintHierarchyWindow();
                    return;
                }
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not change the hierarchy setting '" + name + "': " + e.Message);
            }
        }

        private static bool GetBool(string name)
        {
            return Get(name, false);
        }

        private static void SetBool(string name, bool value)
        {
            Set(name, value);
        }

        private static int GetInt(string name)
        {
            return Get(name, 0);
        }

        private static void SetInt(string name, int value)
        {
            Set(name, value);
        }

        private static string ProjectKey()
        {
            unchecked
            {
                uint hash = 2166136261;
                foreach (var c in Application.dataPath.ToLowerInvariant())
                {
                    hash ^= c;
                    hash *= 16777619;
                }

                return hash.ToString("x8");
            }
        }
    }
}
#endif
