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

namespace WPFMA
{
    [InitializeOnLoad]
    internal static class WPFMAAnimationHighlight
    {
        private const string EnabledKeyPrefix = "WPFMA.Animation.Highlight.";

        private static readonly HashSet<int> Animated = new HashSet<int>();

        private static AnimationClip cachedClip;
        private static GameObject cachedRoot;
        private static int cachedClipVersion = -1;
        private static double nextRefresh;

        private static Type windowType;
        private static bool resolved;

        static WPFMAAnimationHighlight()
        {
            EditorApplication.hierarchyWindowItemOnGUI -= OnHierarchyItem;
            EditorApplication.hierarchyWindowItemOnGUI += OnHierarchyItem;
        }

        // Read for every Hierarchy row on every repaint, so they're kept in memory instead of read from EditorPrefs each time.
        private static bool? enabled;
        private static Color? highlightColor;

        internal static bool Enabled
        {
            get { return (enabled ?? (enabled = EditorPrefs.GetBool(EnabledKeyPrefix + ProjectKey(), true))).Value; }
            set { enabled = value; EditorPrefs.SetBool(EnabledKeyPrefix + ProjectKey(), value); EditorApplication.RepaintHierarchyWindow(); }
        }

        internal static Color HighlightColor
        {
            get
            {
                if (highlightColor != null)
                    return highlightColor.Value;
                var stored = EditorPrefs.GetString(EnabledKeyPrefix + "Color." + ProjectKey(), string.Empty);
                Color parsed;
                highlightColor = !string.IsNullOrEmpty(stored) && ColorUtility.TryParseHtmlString(stored, out parsed)
                    ? parsed
                    : new Color(1f, 0.62f, 0.16f, 0.22f);
                return highlightColor.Value;
            }
            set
            {
                highlightColor = value;
                EditorPrefs.SetString(EnabledKeyPrefix + "Color." + ProjectKey(), "#" + ColorUtility.ToHtmlStringRGBA(value));
                EditorApplication.RepaintHierarchyWindow();
            }
        }

        internal static string Status()
        {
            if (!Enabled)
                return "off";

            if (cachedClip == null)
                return "no clip open in the Animation window, and none selected";

            if (Animated.Count == 0)
                return "'" + cachedClip.name + "' is open, but nothing in the scene matches its paths";

            return "'" + cachedClip.name + "' touches " + Animated.Count +
                   (Animated.Count == 1 ? " object" : " objects") +
                   (cachedRoot != null ? " under " + cachedRoot.name : " (matched across the scene)");
        }

        private static void OnHierarchyItem(int instanceId, Rect selectionRect)
        {
            if (!Enabled)
                return;

            Refresh();

            if (Animated.Count == 0 || !Animated.Contains(instanceId))
                return;

            var color = HighlightColor;

            var tint = new Rect(selectionRect.x - 24f, selectionRect.y, selectionRect.width + 24f, selectionRect.height);
            EditorGUI.DrawRect(tint, color);

            var bar = new Rect(tint.x, selectionRect.y, 2f, selectionRect.height);
            EditorGUI.DrawRect(bar, new Color(color.r, color.g, color.b, Mathf.Min(1f, color.a * 3.5f)));
        }

        private static void Refresh()
        {
            if (EditorApplication.timeSinceStartup < nextRefresh)
                return;

            nextRefresh = EditorApplication.timeSinceStartup + 0.25;

            GameObject root;
            var clip = CurrentClip(out root);

            int version = clip != null ? clip.GetInstanceID() ^ (int)(clip.length * 1000f) : 0;

            if (clip == cachedClip && root == cachedRoot && version == cachedClipVersion)
                return;

            cachedClip = clip;
            cachedRoot = root;
            cachedClipVersion = version;

            Rebuild();
            EditorApplication.RepaintHierarchyWindow();
        }

        private static void Rebuild()
        {
            Animated.Clear();

            if (cachedClip == null)
                return;

            try
            {
                var roots = Roots();

                CollectPaths(AnimationUtility.GetCurveBindings(cachedClip), roots);
                CollectPaths(AnimationUtility.GetObjectReferenceCurveBindings(cachedClip), roots);
            }
            catch (Exception)
            {
            }
        }

        private static void CollectPaths(EditorCurveBinding[] bindings, List<Transform> roots)
        {
            if (bindings == null || roots.Count == 0)
                return;

            foreach (var binding in bindings)
            {
                foreach (var root in roots)
                {
                    if (root == null)
                        continue;

                    var target = string.IsNullOrEmpty(binding.path) ? root : root.Find(binding.path);
                    if (target == null)
                        continue;

                    Animated.Add(target.gameObject.GetInstanceID());

                    if (cachedRoot != null)
                        break;
                }
            }
        }

        private static List<Transform> Roots()
        {
            var roots = new List<Transform>();

            if (cachedRoot != null)
            {
                roots.Add(cachedRoot.transform);
                return roots;
            }

            for (int i = 0; i < UnityEngine.SceneManagement.SceneManager.sceneCount; i++)
            {
                var scene = UnityEngine.SceneManagement.SceneManager.GetSceneAt(i);
                if (!scene.isLoaded)
                    continue;

                foreach (var go in scene.GetRootGameObjects())
                {
                    if (go == null)
                        continue;

                    roots.Add(go.transform);

                    foreach (var child in go.GetComponentsInChildren<Animator>(true))
                    {
                        if (child != null && child.transform != go.transform)
                            roots.Add(child.transform);
                    }
                }
            }

            return roots;
        }

        internal static int AnimatedCount
        {
            get { return Animated.Count; }
        }

        internal static void Reveal()
        {
            Refresh();

            if (Animated.Count == 0)
            {
                Rebuild();

                if (Animated.Count == 0)
                {
                    Debug.LogWarning("[WPFMA-SDK] Nothing to reveal: " + Status());
                    return;
                }
            }

            var targets = new List<UnityEngine.Object>();
            var toExpand = new HashSet<int>();

            foreach (var id in Animated)
            {
                var go = EditorUtility.InstanceIDToObject(id) as GameObject;
                if (go == null)
                    continue;

                targets.Add(go);

                var parent = go.transform.parent;
                while (parent != null)
                {
                    toExpand.Add(parent.gameObject.GetInstanceID());
                    parent = parent.parent;
                }
            }

            if (targets.Count == 0)
            {
                Debug.LogWarning("[WPFMA-SDK] The animated objects are no longer in the scene.");
                return;
            }

            Expand(toExpand);

            Selection.objects = targets.ToArray();
            EditorApplication.RepaintHierarchyWindow();

            Debug.Log("[WPFMA-SDK] Selected " + targets.Count +
                      (targets.Count == 1 ? " object" : " objects") + " animated by '" +
                      (cachedClip != null ? cachedClip.name : "the open clip") + "'.");
        }

        private static void Expand(HashSet<int> ids)
        {
            if (ids.Count == 0)
                return;

            try
            {
                var type = typeof(EditorWindow).Assembly.GetType("UnityEditor.SceneHierarchyWindow", false);
                if (type == null)
                    return;

                var windows = Resources.FindObjectsOfTypeAll(type);
                if (windows == null || windows.Length == 0)
                    return;

                foreach (var window in windows)
                {
                    object target = window;

                    var hierarchyProperty = type.GetProperty("sceneHierarchy",
                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                    if (hierarchyProperty != null)
                    {
                        var hierarchy = hierarchyProperty.GetValue(window, null);
                        if (hierarchy != null)
                            target = hierarchy;
                    }

                    var setExpanded = target.GetType().GetMethod("SetExpanded",
                        BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
                        null, new[] { typeof(int), typeof(bool) }, null);

                    if (setExpanded == null)
                        continue;

                    foreach (var id in ids)
                        setExpanded.Invoke(target, new object[] { id, true });
                }
            }
            catch (Exception e)
            {
                Debug.LogWarning("[WPFMA-SDK] Could not expand the hierarchy: " + e.Message +
                                 " The objects are still selected.");
            }
        }

        private static AnimationClip CurrentClip(out GameObject root)
        {
            root = null;

            try
            {
                if (!Resolve())
                    return SelectedClip();

                var windows = Resources.FindObjectsOfTypeAll(windowType);
                if (windows == null || windows.Length == 0)
                    return SelectedClip();

                var window = windows[0];

                var editorField = windowType.GetField("m_AnimEditor", BindingFlags.Instance | BindingFlags.NonPublic);
                if (editorField == null)
                    return SelectedClip();

                var animEditor = editorField.GetValue(window);
                if (animEditor == null)
                    return SelectedClip();

                var stateMember = animEditor.GetType().GetProperty("state",
                    BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);

                object state = stateMember != null
                    ? stateMember.GetValue(animEditor, null)
                    : GetFieldValue(animEditor, "m_State");

                if (state == null)
                    return SelectedClip();

                var clip = GetMember(state, "activeAnimationClip") as AnimationClip;
                root = GetMember(state, "activeRootGameObject") as GameObject;

                return clip != null ? clip : SelectedClip();
            }
            catch (Exception)
            {
                return SelectedClip();
            }
        }

        private static AnimationClip SelectedClip()
        {
            var clip = Selection.activeObject as AnimationClip;
            if (clip != null)
                return clip;

            foreach (var obj in Selection.objects)
            {
                clip = obj as AnimationClip;
                if (clip != null)
                    return clip;
            }

            return null;
        }

        private static object GetMember(object target, string name)
        {
            var type = target.GetType();

            var property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if (property != null)
                return property.GetValue(target, null);

            return GetFieldValue(target, name);
        }

        private static object GetFieldValue(object target, string name)
        {
            var field = target.GetType().GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            return field != null ? field.GetValue(target) : null;
        }

        private static bool Resolve()
        {
            if (resolved)
                return windowType != null;

            resolved = true;

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                try
                {
                    windowType = assembly.GetType("UnityEditor.AnimationWindow", false);
                    if (windowType != null)
                        break;
                }
                catch (Exception)
                {
                }
            }

            return windowType != null;
        }

        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");
            }
        }
    }
}
#endif
