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

#if WPFMA_VRC_AVATARS
using VRC.SDK3.Avatars.Components;
#endif

namespace WPFMA
{
    /// <summary>
    /// Every animation an avatar uses: the descriptor's layers, plus what Modular Avatar and VRCFury add when it
    /// uploads. The tools used to look only at the descriptor, so they missed the add-ons' toggles: the blendshape
    /// baker could remove a shape a VRCFury toggle moves, and the parameter budget called their parameters unused.
    /// Modular Avatar and VRCFury are read by name, so nothing here needs them installed.
    /// </summary>
    internal static class WPFMAAvatarAnimations
    {
        internal sealed class Source
        {
            public RuntimeAnimatorController Controller;
            public Motion Motion;
            /// <summary>What the animation's paths start from: the avatar, or the object a Modular Avatar merge is set to.</summary>
            public Transform Base;
            /// <summary>Empty for the avatar's own layers; otherwise where it comes from, like "Modular Avatar on 'Hoodie'".</summary>
            public string From = string.Empty;

            public IEnumerable<AnimationClip> Clips
            {
                get
                {
                    var clips = new List<AnimationClip>();
                    if (Controller != null)
                        clips.AddRange(Controller.animationClips);
                    if (Motion != null)
                        Collect(Motion, clips);
                    return clips.Where(c => c != null).Distinct();
                }
            }
        }

        /// <summary>Everything the add-ons point at that isn't laid out as a controller: clips, shape and parameter names.</summary>
        internal sealed class AddOnUse
        {
            public readonly HashSet<AnimationClip> Clips = new HashSet<AnimationClip>();
            public readonly HashSet<string> Shapes = new HashSet<string>(StringComparer.Ordinal);
            public readonly HashSet<string> Parameters = new HashSet<string>(StringComparer.Ordinal);
            public readonly HashSet<RuntimeAnimatorController> Controllers = new HashSet<RuntimeAnimatorController>();
        }

        /// <summary>MMD dance worlds move these shapes by name, so they count as used even when nothing on the avatar animates them.</summary>
        internal static readonly HashSet<string> MmdShapes = new HashSet<string>(StringComparer.Ordinal)
        {
            "あ", "い", "う", "え", "お", "ん", "あ２", "▲", "∧", "□", "ワ", "ω", "ω□",
            "まばたき", "笑い", "ウィンク", "ウィンク右", "ウィンク２",
            "ｳｨﾝｸ２右", "ウィンク２右", "なごみ", "はぅ", "びっくり",
            "じと目", "キリッ", "はちゅ目", "星目", "はぁと", "瞳小",
            "瞳縦潰れ", "光下", "ハイライト消し", "映り込み消し",
            "真面目", "困る", "にこり", "怒り", "上", "下", "前", "照れ", "涙",
            "にやり", "にっこり", "ぺろっ", "てへぺろ", "口角上げ",
            "口角下げ", "口横広げ", "歯無し上", "歯無し下", "悲しむ",
            "喜び", "おこ", "やん"
        };

        /// <summary>Face tracking templates (often added by VRCFury or Modular Avatar at upload) move these by name.</summary>
        internal static bool IsFaceTrackingShape(string name)
        {
            foreach (var standard in WPFMAFaceTrackingChecker.Standards)
                if (Array.IndexOf(standard.Shapes, name) >= 0)
                    return true;
            return false;
        }

        // ---- Remembering scans during a check --------------------------------------------------------------------------
        // A check like the pre-upload check asks for the same scans many times (the add-ons' settings, the animations,
        // the parameters). Inside Cache() each is worked out once per avatar; outside it, every call scans fresh.

        private static Dictionary<string, object> memo;
        private static int memoDepth;

        private sealed class MemoScope : IDisposable
        {
            private bool done;

            public void Dispose()
            {
                if (done)
                    return;
                done = true;
                if (--memoDepth == 0)
                    memo = null;
            }
        }

        /// <summary>Remembers scans until disposed. Only for read-only work: nothing may change the avatar inside it.</summary>
        internal static IDisposable Cache()
        {
            memoDepth++;
            if (memo == null)
                memo = new Dictionary<string, object>();
            return new MemoScope();
        }

        internal static T Memo<T>(string what, UnityEngine.Object owner, Func<T> make)
        {
            if (memo == null || owner == null)
                return make();
            string key = what + "|" + owner.GetInstanceID();
            object found;
            if (memo.TryGetValue(key, out found))
                return (T)found;
            var made = make();
            memo[key] = made;
            return made;
        }

        internal static bool IsAddOn(Component component)
        {
            string ns = component != null ? component.GetType().Namespace : null;
            return ns != null && (ns.StartsWith("nadena.dev", StringComparison.Ordinal) || ns == "VF" || ns.StartsWith("VF.", StringComparison.Ordinal));
        }

        /// <summary>
        /// Every animator and blend tree the avatar plays, with what their paths start from. With addOns, Modular Avatar
        /// merges are included (their paths start from their own object unless they're set to absolute). VRCFury rewrites
        /// its paths itself when it uploads, so its controllers are in Use() instead, not here.
        /// </summary>
        internal static List<Source> Sources(GameObject root, bool addOns)
        {
            return Memo(addOns ? "sources+" : "sources", root, () => FindSources(root, addOns));
        }

        private static List<Source> FindSources(GameObject root, bool addOns)
        {
            var sources = new List<Source>();
            if (root == null)
                return sources;

            var animator = root.GetComponent<Animator>();
            if (animator != null && animator.runtimeAnimatorController != null)
                sources.Add(new Source { Controller = animator.runtimeAnimatorController, Base = root.transform });

#if WPFMA_VRC_AVATARS
            var descriptor = root.GetComponent<VRCAvatarDescriptor>();
            if (descriptor != null)
            {
                foreach (var layer in (descriptor.baseAnimationLayers ?? new VRCAvatarDescriptor.CustomAnimLayer[0])
                         .Concat(descriptor.specialAnimationLayers ?? new VRCAvatarDescriptor.CustomAnimLayer[0]))
                {
                    if (!layer.isDefault && layer.animatorController != null)
                        sources.Add(new Source { Controller = layer.animatorController, Base = root.transform });
                }
            }
#endif

            if (addOns)
            {
                foreach (var component in root.GetComponentsInChildren<Component>(true))
                {
                    if (component == null)
                        continue;

                    string type = component.GetType().Name;
                    if (type != "ModularAvatarMergeAnimator" && type != "ModularAvatarMergeBlendTree")
                        continue;

                    var serialized = new SerializedObject(component);
                    bool tree = type == "ModularAvatarMergeBlendTree";
                    var asset = serialized.FindProperty(tree ? "BlendTree" : "animator");
                    var mode = serialized.FindProperty(tree ? "PathMode" : "pathMode");
                    var pathRoot = serialized.FindProperty(tree ? "RelativePathRoot" : "relativePathRoot");
                    if (asset == null || asset.objectReferenceValue == null)
                        continue;

                    var source = new Source
                    {
                        Controller = asset.objectReferenceValue as RuntimeAnimatorController,
                        Motion = asset.objectReferenceValue as Motion,
                        Base = mode != null && mode.enumValueIndex == 1 ? root.transform : MaBase(root.transform, component.transform, pathRoot),
                        From = "Modular Avatar on '" + component.gameObject.name + "'"
                    };
                    if ((source.Controller != null || source.Motion != null) && source.Base != null)
                        sources.Add(source);
                }
            }

            return sources.GroupBy(s => new { c = (UnityEngine.Object)s.Controller ?? s.Motion, b = s.Base }).Select(g => g.First()).ToList();
        }

        /// <summary>The object a relative Modular Avatar merge's paths start from (the same rules Modular Avatar uses).</summary>
        private static Transform MaBase(Transform avatar, Transform own, SerializedProperty pathRoot)
        {
            if (pathRoot == null)
                return own;

            var target = pathRoot.FindPropertyRelative("targetObject");
            var go = target != null ? target.objectReferenceValue as GameObject : null;
            if (go != null && go.transform.IsChildOf(avatar))
                return go.transform;

            var reference = pathRoot.FindPropertyRelative("referencePath");
            string path = reference != null ? reference.stringValue : null;
            if (string.IsNullOrEmpty(path))
                return own;
            if (path == "$$$AVATAR_ROOT$$$")
                return avatar;

            var found = avatar.Find(path);
            return found != null ? found : own;
        }

        /// <summary>What the add-ons on the avatar point at, read straight from their saved settings.</summary>
        internal static AddOnUse Use(GameObject root)
        {
            return Memo("use", root, () => FindUse(root));
        }

        private static AddOnUse FindUse(GameObject root)
        {
            var use = new AddOnUse();
            if (root == null)
                return use;

            foreach (var component in root.GetComponentsInChildren<Component>(true))
            {
                if (!IsAddOn(component))
                    continue;

                var property = new SerializedObject(component).GetIterator();
                int guard = 0;
                while (property.Next(true) && guard++ < 20000)
                {
                    if (property.propertyType == SerializedPropertyType.ObjectReference)
                    {
                        var value = property.objectReferenceValue;
                        if (value is AnimationClip)
                            use.Clips.Add((AnimationClip)value);
                        else if (value is RuntimeAnimatorController)
                            use.Controllers.Add((RuntimeAnimatorController)value);
                        else if (value is BlendTree)
                        {
                            var clips = new List<AnimationClip>();
                            Collect((BlendTree)value, clips);
                            foreach (var clip in clips)
                                use.Clips.Add(clip);
                        }
                    }
                    else if (property.propertyType == SerializedPropertyType.String && !string.IsNullOrEmpty(property.stringValue))
                    {
                        string path = property.propertyPath.ToLowerInvariant();
                        string name = property.name.ToLowerInvariant();
                        if (name.Contains("blendshape") || name.Contains("shapename"))
                            use.Shapes.Add(property.stringValue);
                        else if (path.Contains("param"))
                            use.Parameters.Add(property.stringValue);
                    }
                }
            }

            foreach (var controller in use.Controllers)
                foreach (var clip in controller.animationClips)
                    if (clip != null)
                        use.Clips.Add(clip);

            foreach (var clip in use.Clips)
                foreach (var binding in AnimationUtility.GetCurveBindings(clip))
                    if (binding.type == typeof(SkinnedMeshRenderer) && binding.propertyName.StartsWith("blendShape.", StringComparison.Ordinal))
                        use.Shapes.Add(binding.propertyName.Substring("blendShape.".Length));

            return use;
        }

        /// <summary>Every animator parameter name in the avatar's controllers, the add-ons' included.</summary>
        internal static HashSet<string> AnimatorParameters(GameObject root, AddOnUse use)
        {
            var names = new HashSet<string>(StringComparer.Ordinal);
            var controllers = Sources(root, true).Select(s => s.Controller).Concat(use.Controllers);
            foreach (var controller in controllers.OfType<AnimatorController>().Distinct())
                foreach (var parameter in controller.parameters)
                    names.Add(parameter.name);

            foreach (var source in Sources(root, true).Where(s => s.Motion is BlendTree))
                CollectParameters((BlendTree)source.Motion, names);
            return names;
        }

        private static void Collect(Motion motion, List<AnimationClip> clips)
        {
            var clip = motion as AnimationClip;
            if (clip != null)
            {
                clips.Add(clip);
                return;
            }

            var tree = motion as BlendTree;
            if (tree == null)
                return;
            foreach (var child in tree.children)
                if (child.motion != null && child.motion != tree)
                    Collect(child.motion, clips);
        }

        private static void CollectParameters(BlendTree tree, HashSet<string> names)
        {
            if (!string.IsNullOrEmpty(tree.blendParameter))
                names.Add(tree.blendParameter);
            if (!string.IsNullOrEmpty(tree.blendParameterY))
                names.Add(tree.blendParameterY);
            foreach (var child in tree.children)
            {
                if (!string.IsNullOrEmpty(child.directBlendParameter))
                    names.Add(child.directBlendParameter);
                var sub = child.motion as BlendTree;
                if (sub != null && sub != tree)
                    CollectParameters(sub, names);
            }
        }
    }
}
#endif
