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

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

namespace WPFMA
{
    /// <summary>
    /// Putting an avatar back in a clean pose (the model's own, the mesh's bind pose, or T-pose) and its blendshapes
    /// back to the model's values or 0, and changing its size with the view position following along.
    /// </summary>
    internal static class WPFMAPoseTools
    {
        /// <summary>Every bone back where the model file has it. Falls back to the bind pose when the avatar isn't from a model.</summary>
        internal static string ResetToModel(GameObject root)
        {
            int moved = 0;
            foreach (var t in root.GetComponentsInChildren<Transform>(true))
            {
                if (t == root.transform)
                    continue;
                var source = PrefabUtility.GetCorrespondingObjectFromOriginalSource(t);
                if (source == null || source == t)
                    continue;
                if (t.localPosition == source.localPosition && t.localRotation == source.localRotation && t.localScale == source.localScale)
                    continue;
                Undo.RecordObject(t, "Reset pose");
                t.localPosition = source.localPosition;
                t.localRotation = source.localRotation;
                t.localScale = source.localScale;
                moved++;
            }

            if (moved == 0 && PrefabUtility.GetCorrespondingObjectFromOriginalSource(root) == null)
                return ResetToBindPose(root);
            return moved == 0 ? "Already in the model's pose." : "Put " + moved + " bone(s) back where the model has them.";
        }

        /// <summary>Every bone where the meshes were bound to it (the pose the model was made in).</summary>
        internal static string ResetToBindPose(GameObject root)
        {
            var poses = new Dictionary<Transform, Matrix4x4>();
            foreach (var skinned in root.GetComponentsInChildren<SkinnedMeshRenderer>(true))
            {
                var mesh = skinned.sharedMesh;
                if (mesh == null)
                    continue;
                var bindposes = mesh.bindposes;
                var bones = skinned.bones;
                for (int i = 0; i < bones.Length && i < bindposes.Length; i++)
                    if (bones[i] != null && bones[i] != root.transform && !poses.ContainsKey(bones[i]))
                        poses[bones[i]] = skinned.transform.localToWorldMatrix * bindposes[i].inverse;
            }

            if (poses.Count == 0)
                return "This avatar has no skinned meshes to take a pose from.";

            // Parents first, so moving a parent doesn't throw off a child already placed.
            foreach (var pair in poses.OrderBy(p => Depth(p.Key)))
            {
                Undo.RecordObject(pair.Key, "Reset to bind pose");
                pair.Key.position = pair.Value.GetColumn(3);
                pair.Key.rotation = pair.Value.rotation;
            }
            return "Put " + poses.Count + " bone(s) in the pose the meshes were made in.";
        }

        /// <summary>The T-pose Unity worked out when it set the model up as Humanoid.</summary>
        internal static string TPose(GameObject root)
        {
            var animator = root.GetComponent<Animator>();
            if (animator == null || animator.avatar == null || !animator.isHuman)
                return "T-pose needs a Humanoid rig.";

            var skeleton = animator.avatar.humanDescription.skeleton;
            var human = animator.avatar.humanDescription.human.Select(h => h.boneName).ToList();
            var byName = new Dictionary<string, Transform>();
            foreach (var t in root.GetComponentsInChildren<Transform>(true))
                if (!byName.ContainsKey(t.name))
                    byName[t.name] = t;

            int moved = 0;
            foreach (var bone in skeleton)
            {
                Transform t;
                if (!human.Contains(bone.name) || !byName.TryGetValue(bone.name, out t) || t == root.transform)
                    continue;
                Undo.RecordObject(t, "T-pose");
                t.localRotation = bone.rotation;
                moved++;
            }

            // The hips keep their height from the model, so the avatar doesn't sink into the floor or float.
            var hips = animator.GetBoneTransform(HumanBodyBones.Hips);
            var hipsBone = skeleton.FirstOrDefault(b => hips != null && b.name == hips.name);
            if (hips != null && hipsBone.name != null)
            {
                Undo.RecordObject(hips, "T-pose");
                hips.localPosition = hipsBone.position;
            }
            return moved == 0 ? "Couldn't match the rig's bones." : "Put " + moved + " bone(s) in T-pose.";
        }

        internal static string ResetBlendshapes(GameObject root, bool toZero)
        {
            int meshes = 0, shapes = 0;
            foreach (var skinned in root.GetComponentsInChildren<SkinnedMeshRenderer>(true))
            {
                var mesh = skinned.sharedMesh;
                if (mesh == null || mesh.blendShapeCount == 0)
                    continue;

                var source = toZero ? null : PrefabUtility.GetCorrespondingObjectFromOriginalSource(skinned);
                bool sameMesh = source != null && source.sharedMesh == mesh;
                bool changed = false;
                for (int i = 0; i < mesh.blendShapeCount; i++)
                {
                    float wanted = sameMesh ? source.GetBlendShapeWeight(i) : 0f;
                    if (Mathf.Approximately(skinned.GetBlendShapeWeight(i), wanted))
                        continue;
                    if (!changed)
                        Undo.RecordObject(skinned, toZero ? "Zero blendshapes" : "Reset blendshapes");
                    skinned.SetBlendShapeWeight(i, wanted);
                    changed = true;
                    shapes++;
                }

                if (changed)
                {
                    PrefabUtility.RecordPrefabInstancePropertyModifications(skinned);
                    meshes++;
                }
            }
            return shapes == 0 ? "Nothing to change." : (toZero ? "Set " : "Put back ") + shapes + " blendshape(s) on " + meshes + " mesh(es)" + (toZero ? " to 0." : " to the model's values.");
        }

        private static int Depth(Transform t)
        {
            int depth = 0;
            for (var p = t.parent; p != null; p = p.parent)
                depth++;
            return depth;
        }

#if WPFMA_VRC_AVATARS
        /// <summary>Scales the avatar and moves its view position with it (VRChat doesn't scale the view position by itself).</summary>
        internal static string Scale(VRCAvatarDescriptor descriptor, float factor)
        {
            if (descriptor == null || factor <= 0f || Mathf.Approximately(factor, 1f))
                return "Nothing to change.";

            var root = descriptor.transform;
            Undo.SetCurrentGroupName("Scale avatar");
            int group = Undo.GetCurrentGroup();
            Undo.RecordObject(root, "Scale avatar");
            Undo.RecordObject(descriptor, "Scale avatar");
            root.localScale *= factor;
            descriptor.ViewPosition *= factor;
            EditorUtility.SetDirty(descriptor);
            PrefabUtility.RecordPrefabInstancePropertyModifications(root);
            PrefabUtility.RecordPrefabInstancePropertyModifications(descriptor);
            Undo.CollapseUndoOperations(group);
            return "Scaled to " + (root.localScale.y * 100f).ToString("0.#") + "% with the eyes at " + descriptor.ViewPosition.y.ToString("0.00") + " m.";
        }
#endif
    }

    internal static class WPFMAPoseToolsSection
    {
        private const string PrefKey = "WPFMA.Tools.PoseToolsExpanded";
        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (!WPFMAToolSection.AvatarProject)
                return;
            WPFMAToolSection.Draw(sectionStyle, "Pose & blendshapes", "reset, T-pose, zero", PrefKey, Body);
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Reset the pose or blendshapes.", "Puts the avatar back in a clean pose, and its blendshapes back to how the model has them (or all to 0). " + "Handy after an animation preview or a tool left it bent."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var root = WPFMAAvatarFolders.AvatarRoot(Selection.activeGameObject);
            if (root == null)
            {
                EditorGUILayout.LabelField("Select the avatar in the Hierarchy.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            var animator = root.GetComponent<Animator>();
            bool human = animator != null && animator.avatar != null && animator.isHuman;
            EditorGUILayout.LabelField("Avatar", root.name, EditorStyles.boldLabel);

            EditorGUILayout.LabelField("Pose", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button(new GUIContent("Model pose", "Every bone back where the model file has it."), GUILayout.Height(24f)))
                    Run(root, "Reset pose", () => WPFMAPoseTools.ResetToModel(root));
                if (GUILayout.Button(new GUIContent("Bind pose", "The pose the meshes were made in."), GUILayout.Height(24f)))
                    Run(root, "Reset to bind pose", () => WPFMAPoseTools.ResetToBindPose(root));
                using (new EditorGUI.DisabledScope(!human))
                    if (GUILayout.Button(new GUIContent("T-pose", human ? "Arms straight out, the pose Unity set the rig up in." : "Needs a Humanoid rig."), GUILayout.Height(24f)))
                        Run(root, "T-pose", () => WPFMAPoseTools.TPose(root));
            }

            EditorGUILayout.Space(2f);
            EditorGUILayout.LabelField("Blendshapes", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button(new GUIContent("Back to the model's", "Every blendshape back to the value the model has."), GUILayout.Height(24f)))
                    Run(root, "Reset blendshapes", () => WPFMAPoseTools.ResetBlendshapes(root, false));
                if (GUILayout.Button(new GUIContent("All to 0", "Every blendshape on every mesh to 0."), GUILayout.Height(24f)))
                    Run(root, "Zero blendshapes", () => WPFMAPoseTools.ResetBlendshapes(root, true));
            }

            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
        }

        private static void Run(GameObject root, string action, System.Func<string> change)
        {
            EditorApplication.delayCall += () =>
            {
                status = WPFMAChangeLog.Run("Pose & blendshapes", action + " on '" + root.name + "'", null, true, change);
                SceneView.RepaintAll();
            };
        }
    }

    internal static class WPFMAScaleSection
    {
        private const string PrefKey = "WPFMA.Tools.ScaleExpanded";

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (!WPFMAToolSection.AvatarProject)
                return;
            WPFMAToolSection.Draw(sectionStyle, "Avatar size", 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 float wantedHeight = -1f;
        private static VRCAvatarDescriptor heightFor;
        private static string status;

        private static VRCAvatarDescriptor Avatar()
        {
            var active = Selection.activeGameObject;
            return active != null && !EditorUtility.IsPersistent(active) ? active.GetComponentInParent<VRCAvatarDescriptor>() : null;
        }

        private static string Detail()
        {
            var avatar = Avatar();
            return avatar == null ? "select an avatar" : "eyes at " + avatar.ViewPosition.y.ToString("0.00") + " m";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Resize the avatar; the view follows.", "Makes the avatar bigger or smaller, and moves the view position with it so you see from the eyes at the new size."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            var avatar = Avatar();
            if (avatar == null)
            {
                EditorGUILayout.LabelField(new GUIContent("Select an avatar.", "Select the avatar (anything with a VRC Avatar Descriptor) in the Hierarchy."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            float eyes = avatar.ViewPosition.y;
            if (heightFor != avatar || wantedHeight < 0f)
            {
                heightFor = avatar;
                wantedHeight = eyes;
            }

            EditorGUILayout.LabelField("Avatar", avatar.name, EditorStyles.boldLabel);
            EditorGUILayout.LabelField("Now: " + (avatar.transform.localScale.y * 100f).ToString("0.#") + "% size, eyes at " + eyes.ToString("0.00") + " m.",
                WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

            if (eyes <= 0.01f)
            {
                EditorGUILayout.LabelField(new GUIContent("Set the view position first.", "Set the view position first (Avatar setup does it), so the size can be worked out from the eye height."), WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
                return;
            }

            wantedHeight = Mathf.Max(0.05f, EditorGUILayout.FloatField("New eye height (m)", wantedHeight));
            using (new EditorGUILayout.HorizontalScope())
            {
                foreach (var percent in new[] { 50, 90, 110, 150, 200 })
                    if (GUILayout.Button(percent + "%", EditorStyles.miniButton))
                        wantedHeight = eyes * percent / 100f;
            }

            float factor = wantedHeight / eyes;
            using (new EditorGUI.DisabledScope(Mathf.Abs(factor - 1f) < 0.001f))
            {
                if (GUILayout.Button("Resize to " + (factor * 100f).ToString("0.#") + "%", GUILayout.Height(26f)))
                {
                    var target = avatar;
                    EditorApplication.delayCall += () =>
                    {
                        status = WPFMAChangeLog.Run("Avatar size", "Resize '" + target.name + "'", null, true, () => WPFMAPoseTools.Scale(target, factor));
                        wantedHeight = -1f;
                        Debug.Log("[WPFMA-SDK] " + status);
                    };
                }
            }

            EditorGUILayout.LabelField(new GUIContent("PhysBones and colliders scale too.", "PhysBones, contacts and colliders on the avatar scale with it. A tall avatar can drop a performance rank on bounds."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            if (!string.IsNullOrEmpty(status))
                EditorGUILayout.LabelField(status, WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
        }
#endif
    }
}
#endif
