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

namespace WPFMA
{
    [InitializeOnLoad]
    internal static class WPFMALayerWeight
    {
        private const string EnabledKeyPrefix = "WPFMA.LayerWeight.";

        private static readonly Dictionary<int, int> LayerCounts = new Dictionary<int, 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 WPFMALayerWeight()
        {
            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;

            var layers = controller.layers;
            int changed = 0;

            for (int i = 0; i < layers.Length; i++)
            {
                if (layers[i] == null || layers[i].defaultWeight > 0f)
                    continue;

                layers[i].defaultWeight = 1f;
                changed++;
            }

            if (changed > 0)
            {
                Undo.RecordObject(controller, "Set layer weight");
                controller.layers = layers;
                EditorUtility.SetDirty(controller);
            }

            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 layers = controller.layers;

                int previous;
                bool known = LayerCounts.TryGetValue(id, out previous);
                LayerCounts[id] = layers.Length;

                // Only act on a layer that appeared just now. Weights already at zero
                // are somebody's decision - plenty of rigs drive a layer's weight from
                // an Animator Layer Control behaviour, and rewriting those would break
                // the avatar.
                if (!known || layers.Length <= previous)
                    continue;

                bool changed = false;
                for (int i = previous; i < layers.Length; i++)
                {
                    if (layers[i] == null || layers[i].defaultWeight > 0f)
                        continue;

                    layers[i].defaultWeight = 1f;
                    changed = true;
                }

                if (!changed)
                    continue;

                controller.layers = layers;
                EditorUtility.SetDirty(controller);

                Debug.Log("[WPFMA-SDK] New layer on '" + controller.name + "' set to weight 1. " +
                          "Turn this off in Settings > Animator if you would rather it stayed at 0.");
            }
        }

        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
