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

namespace WPFMA
{
    [InitializeOnLoad]
    internal static class WPFMATransitionDefaults
    {
        private const string EnabledKeyPrefix = "WPFMA.Transitions.Instant.";

        private static readonly Dictionary<int, HashSet<int>> Known = new Dictionary<int, HashSet<int>>();
        private static double nextCheck;
        private static bool? enabled;
        // A controller's dirty count when it was last looked at; unchanged means nothing to look at again.
        private static readonly Dictionary<int, int> LastDirty = new Dictionary<int, int>();

        static WPFMATransitionDefaults()
        {
            EditorApplication.update -= Tick;
            EditorApplication.update += Tick;
        }

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

        internal static int FixAll(AnimatorController controller)
        {
            if (controller == null)
                return 0;

            int changed = 0;

            foreach (var transition in Collect(controller))
            {
                if (MakeInstant(transition))
                    changed++;
            }

            if (changed > 0)
            {
                EditorUtility.SetDirty(controller);
                AssetDatabase.SaveAssets();
            }

            return changed;
        }

        private static void Tick()
        {
            if (EditorApplication.timeSinceStartup < nextCheck || !Enabled)
                return;

            nextCheck = EditorApplication.timeSinceStartup + 0.3;

            foreach (var controller in WPFMAAnimatorTargets.Candidates())
            {
                if (controller == null)
                    continue;

                int id = controller.GetInstanceID();
                int dirty = EditorUtility.GetDirtyCount(controller);
                int lastDirty;
                if (LastDirty.TryGetValue(id, out lastDirty) && lastDirty == dirty)
                    continue;
                LastDirty[id] = dirty;
                var transitions = Collect(controller);

                HashSet<int> seen;
                bool first = !Known.TryGetValue(id, out seen);

                if (first)
                {
                    // Record what is already there without touching it. Existing
                    // transitions are somebody's tuning, not ours to rewrite.
                    seen = new HashSet<int>();
                    foreach (var transition in transitions)
                        seen.Add(transition.GetInstanceID());

                    Known[id] = seen;
                    continue;
                }

                int changed = 0;
                foreach (var transition in transitions)
                {
                    int transitionId = transition.GetInstanceID();
                    if (!seen.Add(transitionId))
                        continue;

                    if (MakeInstant(transition))
                        changed++;
                }

                if (changed == 0)
                    continue;

                EditorUtility.SetDirty(controller);
                Debug.Log("[WPFMA-SDK] " + changed + " new transition(s) on '" + controller.name +
                          "' set to instant. Turn this off in Settings > Animator.");
            }
        }

        private static bool MakeInstant(AnimatorStateTransition transition)
        {
            if (transition == null)
                return false;

            if (!transition.hasExitTime && transition.duration == 0f &&
                transition.offset == 0f && !transition.hasFixedDuration)
                return false;

            Undo.RecordObject(transition, "Instant transition");

            transition.hasExitTime = false;
            transition.exitTime = 0f;
            transition.hasFixedDuration = false;
            transition.duration = 0f;
            transition.offset = 0f;

            EditorUtility.SetDirty(transition);
            return true;
        }

        private static List<AnimatorStateTransition> Collect(AnimatorController controller)
        {
            var found = new List<AnimatorStateTransition>();

            foreach (var layer in controller.layers)
            {
                if (layer != null && layer.stateMachine != null)
                    Walk(layer.stateMachine, found, new HashSet<int>());
            }

            return found;
        }

        private static void Walk(AnimatorStateMachine machine, List<AnimatorStateTransition> found, HashSet<int> seen)
        {
            if (machine == null || !seen.Add(machine.GetInstanceID()))
                return;

            foreach (var child in machine.states)
            {
                if (child.state == null)
                    continue;

                foreach (var transition in child.state.transitions)
                {
                    if (transition != null)
                        found.Add(transition);
                }
            }

            foreach (var transition in machine.anyStateTransitions)
            {
                if (transition != null)
                    found.Add(transition);
            }

            foreach (var child in machine.stateMachines)
                Walk(child.stateMachine, found, seen);
        }

        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
