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

namespace WPFMA
{
    internal static class WPFMAAnimatorTargets
    {
        private static List<AnimatorController> cached;
        private static double cachedUntil;
        private static int cachedSelection = -1;

        /// <summary>
        /// The controllers in reach: selected, on the selected objects, or open in the Animator window. Two helpers ask
        /// every 0.3 seconds, so the answer is kept for a quarter second (or until the selection changes).
        /// </summary>
        internal static IEnumerable<AnimatorController> Candidates()
        {
            int selection = Selection.activeInstanceID ^ Selection.count;
            if (cached != null && EditorApplication.timeSinceStartup < cachedUntil && selection == cachedSelection)
                return cached;
            cached = Find().ToList();
            cachedUntil = EditorApplication.timeSinceStartup + 0.25;
            cachedSelection = selection;
            return cached;
        }

        private static IEnumerable<AnimatorController> Find()
        {
            var seen = new HashSet<int>();

            var selected = Selection.activeObject as AnimatorController;
            if (selected != null && seen.Add(selected.GetInstanceID()))
                yield return selected;

            foreach (var go in Selection.gameObjects)
            {
                if (go == null)
                    continue;

                foreach (var animator in go.GetComponentsInChildren<Animator>(true))
                {
                    var controller = animator != null ? animator.runtimeAnimatorController as AnimatorController : null;
                    if (controller != null && seen.Add(controller.GetInstanceID()))
                        yield return controller;
                }
            }

            var open = OpenInAnimatorWindow();
            if (open != null && seen.Add(open.GetInstanceID()))
                yield return open;
        }

        private static bool resolved;
        private static Type windowType;
        private static PropertyInfo controllerProperty;
        private static FieldInfo controllerField;
        private static UnityEngine.Object window;
        private static double nextWindowSearch;

        private static AnimatorController OpenInAnimatorWindow()
        {
            try
            {
                if (!resolved)
                {
                    resolved = true;
                    windowType = typeof(EditorWindow).Assembly.GetType("UnityEditor.Graphs.AnimatorControllerTool", false);
                    if (windowType != null)
                    {
                        controllerProperty = windowType.GetProperty("animatorController", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                        controllerField = windowType.GetField("m_AnimatorController", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
                    }
                }
                if (windowType == null)
                    return null;

                // Searching every loaded object for the window is slow, so it's only done once a second (or when it closed).
                if (window == null && EditorApplication.timeSinceStartup >= nextWindowSearch)
                {
                    nextWindowSearch = EditorApplication.timeSinceStartup + 1.0;
                    var windows = Resources.FindObjectsOfTypeAll(windowType);
                    window = windows != null && windows.Length > 0 ? windows[0] : null;
                }
                if (window == null)
                    return null;

                if (controllerProperty != null)
                    return controllerProperty.GetValue(window, null) as AnimatorController;
                return controllerField != null ? controllerField.GetValue(window) as AnimatorController : null;
            }
            catch (Exception)
            {
                return null;
            }
        }
    }
}
#endif
