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

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

namespace WPFMA
{
#if WPFMA_VRC_AVATARS
    /// <summary>
    /// Write Defaults checker and fix. Mixing Write Defaults on and off in one controller is the classic cause of toggles
    /// that stick and faces that freeze. Checks every playable layer's controller (and Modular Avatar's Merge Animator
    /// controllers, which are merged in at upload), and makes a controller all on or all off. Direct blend trees always
    /// stay on (they only work that way). Going to off gives empty states a reset clip, so a toggle's "off" state still
    /// turns things back off instead of keeping whatever was there before.
    /// </summary>
    internal static class WPFMAWriteDefaults
    {
        internal sealed class LayerReport
        {
            public string Name;
            public int On;
            public int Off;
            public int Empty;
            public int DirectOff;
            public bool Animated;
        }

        internal sealed class ControllerReport
        {
            public string Label;
            public AnimatorController Controller;
            public string Path;
            public bool ReadOnly;
            public readonly List<LayerReport> Layers = new List<LayerReport>();
            public int On;
            public int Off;
            public int Empty;
            public int DirectOff;

            /// <summary>Modular Avatar's Merge Animator this came from (null for the avatar's own layers).</summary>
            public Component MergeAnimator;
            public bool MatchesAvatar;
            /// <summary>For a Merge Animator: the avatar's own setting in the layer it merges into (null if unknown or mixed).</summary>
            public bool? AvatarSetting;

            public bool Mixed
            {
                get { return On > 0 && Off > 0; }
            }

            /// <summary>The setting most of its states already use (off on a tie, as VRChat recommends).</summary>
            public bool Recommended
            {
                get { return On > Off; }
            }

            public bool HasProblem
            {
                get
                {
                    if (MergeAnimator != null)
                        return !MatchesAvatar && AvatarSetting.HasValue && (Mixed || (On > 0 && AvatarSetting == false) || (Off > 0 && AvatarSetting == true));
                    return Mixed || DirectOff > 0;
                }
            }

            /// <summary>Layers whose states go against the recommended setting.</summary>
            public IEnumerable<LayerReport> OddLayers
            {
                get { return Layers.Where(l => l.Animated && (Recommended ? l.Off > 0 : l.On > 0)); }
            }
        }

        internal static List<ControllerReport> Check(VRCAvatarDescriptor avatar)
        {
            var reports = new List<ControllerReport>();
            if (avatar == null)
                return reports;
            var own = new Dictionary<VRCAvatarDescriptor.AnimLayerType, ControllerReport>();
            if (avatar.baseAnimationLayers != null)
            {
                foreach (var layer in avatar.baseAnimationLayers)
                {
                    var controller = layer.animatorController as AnimatorController;
                    if (layer.isDefault || controller == null)
                        continue;
                    var report = Analyze(controller, layer.type.ToString());
                    reports.Add(report);
                    own[layer.type] = report;
                }
            }

            // Modular Avatar merges these into a layer at upload; read by name so it works without it installed.
            foreach (var component in avatar.GetComponentsInChildren<Component>(true))
            {
                if (component == null || component.GetType().Name != "ModularAvatarMergeAnimator")
                    continue;
                var serialized = new SerializedObject(component);
                var asset = serialized.FindProperty("animator");
                var controller = asset != null ? asset.objectReferenceValue as AnimatorController : null;
                if (controller == null)
                    continue;
                var match = serialized.FindProperty("matchAvatarWriteDefaults");
                var layerType = serialized.FindProperty("layerType");
                var report = Analyze(controller, "Merge Animator on '" + component.gameObject.name + "'");
                report.MergeAnimator = component;
                report.MatchesAvatar = match != null && match.boolValue;
                ControllerReport target;
                VRCAvatarDescriptor.AnimLayerType type = VRCAvatarDescriptor.AnimLayerType.FX;
                if (layerType != null)
                    type = (VRCAvatarDescriptor.AnimLayerType)layerType.intValue;
                if (own.TryGetValue(type, out target) && !target.Mixed && target.On + target.Off > 0)
                    report.AvatarSetting = target.On > 0;
                reports.Add(report);
            }
            return reports;
        }

        private static ControllerReport Analyze(AnimatorController controller, string label)
        {
            string path = AssetDatabase.GetAssetPath(controller);
            var report = new ControllerReport
            {
                Label = label,
                Controller = controller,
                Path = path,
                ReadOnly = path.StartsWith("Packages/", StringComparison.Ordinal)
            };
            foreach (var layer in controller.layers)
            {
                if (layer.stateMachine == null)
                    continue;
                var states = AllStates(layer.stateMachine).Where(s => s != null).ToList();
                var lr = new LayerReport { Name = layer.name, Animated = states.Any(s => s.motion != null) };
                foreach (var state in states)
                {
                    if (IsDirect(state.motion))
                    {
                        if (!state.writeDefaultValues)
                            lr.DirectOff++;
                        continue;
                    }
                    // A layer with no animation at all (only parameter drivers and such): its setting doesn't matter.
                    if (!lr.Animated)
                        continue;
                    if (state.writeDefaultValues)
                        lr.On++;
                    else
                        lr.Off++;
                    if (state.motion == null)
                        lr.Empty++;
                }
                report.Layers.Add(lr);
                report.On += lr.On;
                report.Off += lr.Off;
                report.Empty += lr.Empty;
                report.DirectOff += lr.DirectOff;
            }
            return report;
        }

        /// <summary>
        /// Makes a controller all on or all off (Direct blend trees always on), or for a Merge Animator turns on
        /// "Match avatar write defaults". Returns what was done; created lists any reset clips it made.
        /// </summary>
        internal static string Fix(VRCAvatarDescriptor avatar, ControllerReport report, bool on, List<string> created)
        {
            if (report.MergeAnimator != null)
            {
                var serialized = new SerializedObject(report.MergeAnimator);
                var match = serialized.FindProperty("matchAvatarWriteDefaults");
                if (match == null)
                    return "This Modular Avatar version has no 'Match avatar write defaults' setting.";
                match.boolValue = true;
                serialized.ApplyModifiedProperties();
                return "Turned on 'Match avatar write defaults' on " + report.MergeAnimator.gameObject.name + ": Modular Avatar matches it to the avatar at upload.";
            }
            if (report.ReadOnly)
                return report.Controller.name + " is VRChat's own (in Packages) and can't be changed. Give the avatar a copy of it first.";

            var controller = report.Controller;
            int changed = 0, resets = 0;
            var undo = new List<UnityEngine.Object>();
            foreach (var layer in controller.layers.Where(l => l.stateMachine != null))
                undo.AddRange(AllStates(layer.stateMachine).Where(s => s != null).Cast<UnityEngine.Object>());
            Undo.RecordObjects(undo.ToArray(), "Write defaults " + (on ? "on" : "off"));

            foreach (var layer in controller.layers)
            {
                if (layer.stateMachine == null)
                    continue;
                var states = AllStates(layer.stateMachine).Where(s => s != null).ToList();
                bool animated = states.Any(s => s.motion != null);
                AnimationClip reset = null;
                foreach (var state in states)
                {
                    bool want = IsDirect(state.motion) || on;
                    if (!animated && !IsDirect(state.motion))
                        continue;
                    if (state.writeDefaultValues != want)
                    {
                        state.writeDefaultValues = want;
                        EditorUtility.SetDirty(state);
                        changed++;
                    }
                    // Off: an empty state no longer puts things back by itself, so it gets a clip that does.
                    if (!want && state.motion == null && animated)
                    {
                        if (reset == null)
                            reset = MakeResetClip(avatar, controller, layer, states, created);
                        if (reset != null)
                        {
                            state.motion = reset;
                            EditorUtility.SetDirty(state);
                            resets++;
                        }
                    }
                }
            }
            EditorUtility.SetDirty(controller);
            AssetDatabase.SaveAssets();
            return "Made " + controller.name + " all " + (on ? "on" : "off") + " (" + changed + " state" + (changed == 1 ? "" : "s") + " changed" +
                   (resets > 0 ? ", " + resets + " empty state" + (resets == 1 ? "" : "s") + " given a reset clip" : "") + "). Direct blend trees stay on.";
        }

        /// <summary>
        /// A clip that sets everything the layer animates back to how it is on the avatar now (its rest values), for
        /// empty states once Write Defaults is off. Null when there's nothing to reset.
        /// </summary>
        private static AnimationClip MakeResetClip(VRCAvatarDescriptor avatar, AnimatorController controller, AnimatorControllerLayer layer,
                                                   List<AnimatorState> states, List<string> created)
        {
            var floats = new Dictionary<string, EditorCurveBinding>();
            var objects = new Dictionary<string, EditorCurveBinding>();
            foreach (var clip in states.SelectMany(s => Clips(s.motion)).Distinct())
            {
                foreach (var b in AnimationUtility.GetCurveBindings(clip))
                    floats[b.path + "|" + b.type.FullName + "|" + b.propertyName] = b;
                foreach (var b in AnimationUtility.GetObjectReferenceCurveBindings(clip))
                    objects[b.path + "|" + b.type.FullName + "|" + b.propertyName] = b;
            }
            if (floats.Count + objects.Count == 0)
                return null;

            var reset = new AnimationClip { name = controller.name + " - " + layer.name + " reset" };
            var root = avatar.gameObject;
            int written = 0;
            foreach (var b in floats.Values)
            {
                float value;
                if (!AnimationUtility.GetFloatValue(root, b, out value))
                    continue;
                AnimationUtility.SetEditorCurve(reset, b, new AnimationCurve(new Keyframe(0f, value), new Keyframe(1f / 60f, value)));
                written++;
            }
            foreach (var b in objects.Values)
            {
                UnityEngine.Object value;
                if (!AnimationUtility.GetObjectReferenceValue(root, b, out value))
                    continue;
                AnimationUtility.SetObjectReferenceCurve(reset, b, new[]
                {
                    new ObjectReferenceKeyframe { time = 0f, value = value },
                    new ObjectReferenceKeyframe { time = 1f / 60f, value = value }
                });
                written++;
            }
            if (written == 0)
                return null;

            string folder = Path.GetDirectoryName(AssetDatabase.GetAssetPath(controller)).Replace('\\', '/') + "/WPFMA WD Reset";
            if (!AssetDatabase.IsValidFolder(folder))
                AssetDatabase.CreateFolder(Path.GetDirectoryName(folder).Replace('\\', '/'), "WPFMA WD Reset");
            string path = AssetDatabase.GenerateUniqueAssetPath(folder + "/" + WPFMAPaths.SafeFileName(reset.name) + ".anim");
            AssetDatabase.CreateAsset(reset, path);
            if (created != null)
                created.Add(path);
            return reset;
        }

        private static bool IsDirect(Motion motion)
        {
            var tree = motion as BlendTree;
            return tree != null && tree.blendType == BlendTreeType.Direct;
        }

        private static IEnumerable<AnimationClip> Clips(Motion motion)
        {
            var clip = motion as AnimationClip;
            if (clip != null)
            {
                yield return clip;
                yield break;
            }
            var tree = motion as BlendTree;
            if (tree == null)
                yield break;
            foreach (var child in tree.children)
                foreach (var inner in Clips(child.motion))
                    yield return inner;
        }

        internal static IEnumerable<AnimatorState> AllStates(AnimatorStateMachine machine)
        {
            foreach (var child in machine.states)
                yield return child.state;
            foreach (var sub in machine.stateMachines)
            {
                if (sub.stateMachine == null)
                    continue;
                foreach (var state in AllStates(sub.stateMachine))
                    yield return state;
            }
        }
    }
#endif

    /// <summary>The Write defaults tool on the Tools tab.</summary>
    internal static class WPFMAWriteDefaultsSection
    {
        internal const string PrefKey = "WPFMA.Tools.WriteDefaultsExpanded";

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (!WPFMAToolSection.AvatarProject)
                return;
            WPFMAToolSection.Draw(sectionStyle, "Write defaults", Detail(), PrefKey, Body);
        }

#if !WPFMA_VRC_AVATARS
        private static string Detail()
        {
            return "needs the avatar SDK";
        }

        private static void Body()
        {
            EditorGUILayout.HelpBox("This needs the VRChat avatar SDK, which is not in this project yet.", MessageType.Info);
        }
#else
        private static VRCAvatarDescriptor checkedAvatar;
        private static List<WPFMAWriteDefaults.ControllerReport> reports;
        private static string status;
        private static bool statusIsError;

        private static string Detail()
        {
            if (reports == null || checkedAvatar == null)
                return "not checked yet";
            int problems = reports.Count(r => r.HasProblem);
            return problems == 0 ? "all consistent" : problems + " to fix";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Finds mixed Write Defaults and fixes them.",
                "Mixing Write Defaults on and off in one controller makes toggles stick and faces freeze. This checks every " +
                "controller on the avatar (and Modular Avatar's Merge Animators) and makes each one all on or all off."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var active = Selection.activeGameObject;
            var avatar = active != null && !EditorUtility.IsPersistent(active) ? active.GetComponentInParent<VRCAvatarDescriptor>() : null;
            if (avatar == null)
            {
                EditorGUILayout.LabelField("Select the avatar in the Hierarchy.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }
            if (avatar != checkedAvatar)
            {
                checkedAvatar = avatar;
                reports = WPFMAWriteDefaults.Check(avatar);
                status = null;
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Avatar", avatar.name, EditorStyles.boldLabel);
                if (GUILayout.Button("Check again", GUILayout.Width(110f)))
                {
                    reports = WPFMAWriteDefaults.Check(avatar);
                    status = null;
                }
            }

            if (reports == null || reports.Count == 0)
            {
                EditorGUILayout.LabelField("No controllers on this avatar yet (it uses VRChat's defaults).", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }
            else
            {
                foreach (var report in reports)
                    DrawReport(avatar, report);
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(statusIsError ? WPFMAToolSection.WarnAmber : WPFMAToolSection.OkGreen));
            EditorGUILayout.LabelField(new GUIContent("Direct blend trees always stay on.",
                "Direct blend trees (like WPFMA's combined toggles) only work with Write Defaults on, so they're left on whatever the rest " +
                "uses, and aren't counted as mixing."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
        }

        private static void DrawReport(VRCAvatarDescriptor avatar, WPFMAWriteDefaults.ControllerReport report)
        {
            EditorGUILayout.Space(4f);
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(new GUIContent(report.Label, report.Path), EditorStyles.boldLabel, GUILayout.Width(Mathf.Min(220f, EditorGUIUtility.currentViewWidth * 0.4f)));
                string counts = report.Off + " off · " + report.On + " on";
                bool ok = !report.HasProblem;
                EditorGUILayout.LabelField(counts + (ok ? "  ·  fine" : report.MergeAnimator != null ? "  ·  doesn't match the avatar" : report.Mixed ? "  ·  mixed" : "  ·  needs a fix"),
                    WPFMAToolSection.Hint(ok ? WPFMAToolSection.OkGreen : WPFMAToolSection.WarnAmber));
                if (GUILayout.Button(new GUIContent("Show", "Select the controller in the Project window"), EditorStyles.miniButton, GUILayout.Width(48f)))
                    EditorGUIUtility.PingObject(report.Controller);
            }
            if (!report.HasProblem)
                return;

            using (new EditorGUI.IndentLevelScope())
            {
                if (report.MergeAnimator != null)
                {
                    EditorGUILayout.LabelField("Merged into the avatar at upload with " + (report.Mixed ? "mixed" : report.On > 0 ? "on" : "off") +
                                               ", while the avatar uses " + (report.AvatarSetting == true ? "on" : "off") + ".", WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
                    if (GUILayout.Button("Turn on 'Match avatar write defaults'", GUILayout.Width(260f)))
                        RunFix(avatar, report, true);
                    return;
                }

                var odd = report.OddLayers.ToList();
                if (odd.Count > 0)
                    EditorGUILayout.LabelField(new GUIContent("Odd ones out: " + string.Join(", ", odd.Take(4).Select(l => "'" + l.Name + "'").ToArray()) + (odd.Count > 4 ? " and " + (odd.Count - 4) + " more" : ""),
                        string.Join("\n", odd.Select(l => l.Name + ": " + l.Off + " off, " + l.On + " on").ToArray())), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
                if (report.DirectOff > 0)
                    EditorGUILayout.LabelField(report.DirectOff + " Direct blend tree state" + (report.DirectOff == 1 ? " has" : "s have") + " it off; they only work with it on.", WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                if (report.ReadOnly)
                {
                    EditorGUILayout.LabelField("This is VRChat's own controller (in Packages) and can't be changed. Give the avatar a copy of it first.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                    return;
                }
                bool rec = report.Recommended;
                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.Space(EditorGUI.indentLevel * 15f);
                    if (GUILayout.Button(new GUIContent(rec ? "Make all Off" : "Make all Off (recommended)",
                            "Empty states get a clip that puts things back, so toggles still turn off."), GUILayout.Width(190f)))
                        RunFix(avatar, report, false);
                    if (GUILayout.Button(new GUIContent(rec ? "Make all On (recommended)" : "Make all On", "Safe for toggles; every state writes defaults."), GUILayout.Width(190f)))
                        RunFix(avatar, report, true);
                }
                if (report.Empty > 0 && report.On > 0)
                    EditorGUILayout.LabelField(report.Empty + " empty state" + (report.Empty == 1 ? "" : "s") + " (no animation): Make all Off gives them a reset clip.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }
        }

        private static void RunFix(VRCAvatarDescriptor avatar, WPFMAWriteDefaults.ControllerReport report, bool on)
        {
            EditorApplication.delayCall += () =>
            {
                var created = new List<string>();
                string message = null;
                var assets = new List<string>();
                if (report.MergeAnimator == null)
                    assets.Add(report.Path);
                WPFMAChangeLog.Run("Write defaults", (report.MergeAnimator != null ? "Match avatar write defaults on '" + report.MergeAnimator.gameObject.name + "'" :
                        "Make " + report.Controller.name + " all " + (on ? "on" : "off")), assets, report.MergeAnimator != null,
                    () => message = WPFMAWriteDefaults.Fix(avatar, report, on, created), () => created);
                status = message;
                statusIsError = false;
                reports = WPFMAWriteDefaults.Check(avatar);
                Debug.Log("[WPFMA-SDK] " + message);
            };
        }
#endif
    }
}
#endif
