// 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;

namespace WPFMA
{
    /// <summary>
    /// Lighting and bounds that match across the avatar. Each mesh picks up world lighting at its own anchor, so
    /// meshes with different (or no) anchors light differently - the body one shade, the outfit another. And a
    /// skinned mesh whose bounds don't cover it disappears at some camera angles. This gives every mesh the same
    /// anchor and bounds that cover the whole avatar.
    /// </summary>
    internal static class WPFMABoundsFix
    {
        internal static readonly string[] AnchorNames = { "Chest", "Hips", "Head" };

        internal sealed class State
        {
            public int Renderers;
            public int Anchors;
            public int WithoutAnchor;
            public int ShortBounds;
            public Transform Anchor;

            public bool NeedsFix
            {
                get { return Renderers > 1 && (Anchors > 1 || WithoutAnchor > 0 || ShortBounds > 0); }
            }
        }

        internal static List<Renderer> Renderers(GameObject root)
        {
            return root.GetComponentsInChildren<Renderer>(true)
                .Where(r => r is SkinnedMeshRenderer || r is MeshRenderer)
                .Where(r => !r.CompareTag("EditorOnly"))
                .ToList();
        }

        /// <summary>The bone every mesh's lighting follows: chest, hips or head (hips, then the avatar, if it's missing).</summary>
        internal static Transform AnchorFor(GameObject root, int choice)
        {
            var animator = root.GetComponent<Animator>();
            if (animator != null && animator.isHuman)
            {
                var wanted = choice == 1 ? HumanBodyBones.Hips : choice == 2 ? HumanBodyBones.Head : HumanBodyBones.Chest;
                var bone = animator.GetBoneTransform(wanted) ?? animator.GetBoneTransform(HumanBodyBones.Hips);
                if (bone != null)
                    return bone;
            }
            return root.transform;
        }

        internal static State Inspect(GameObject root, int choice)
        {
            var state = new State();
            if (root == null)
                return state;

            var renderers = Renderers(root);
            state.Renderers = renderers.Count;
            state.Anchor = AnchorFor(root, choice);
            state.WithoutAnchor = renderers.Count(r => r.probeAnchor == null);
            state.Anchors = renderers.Select(r => r.probeAnchor).Distinct().Count();

            foreach (var skinned in renderers.OfType<SkinnedMeshRenderer>())
            {
                Bounds own;
                if (MeshBounds(skinned, out own) && !Covers(skinned.bounds, own))
                    state.ShortBounds++;
            }
            return state;
        }

        internal static string Apply(GameObject root, int choice, bool fixBounds)
        {
            var renderers = Renderers(root);
            var anchor = AnchorFor(root, choice);

            Undo.SetCurrentGroupName("Fix bounds and lighting");
            int group = Undo.GetCurrentGroup();

            int anchored = 0, bounded = 0;
            foreach (var renderer in renderers)
            {
                if (renderer.probeAnchor == anchor)
                    continue;
                Undo.RecordObject(renderer, "Fix bounds and lighting");
                renderer.probeAnchor = anchor;
                PrefabUtility.RecordPrefabInstancePropertyModifications(renderer);
                anchored++;
            }

            if (fixBounds)
            {
                // One box around the whole avatar as it stands now, a little bigger so moving arms and hair stay inside.
                bool any = false;
                var all = new Bounds();
                foreach (var renderer in renderers)
                {
                    Bounds own;
                    var skinned = renderer as SkinnedMeshRenderer;
                    if (skinned != null)
                    {
                        if (!MeshBounds(skinned, out own))
                            continue;
                    }
                    else
                    {
                        own = renderer.bounds;
                        if (own.size == Vector3.zero)
                            continue;
                    }

                    if (!any)
                        all = own;
                    else
                        all.Encapsulate(own);
                    any = true;
                }

                if (any)
                {
                    all.Expand(all.size * 0.1f);
                    var animator = root.GetComponent<Animator>();
                    var hips = animator != null && animator.isHuman ? animator.GetBoneTransform(HumanBodyBones.Hips) : null;

                    foreach (var skinned in renderers.OfType<SkinnedMeshRenderer>())
                    {
                        Undo.RecordObject(skinned, "Fix bounds and lighting");
                        if (skinned.rootBone == null)
                            skinned.rootBone = hips != null ? hips : root.transform;
                        skinned.localBounds = ToLocal(skinned.rootBone, all);
                        skinned.updateWhenOffscreen = false;
                        PrefabUtility.RecordPrefabInstancePropertyModifications(skinned);
                        bounded++;
                    }
                }
            }

            Undo.CollapseUndoOperations(group);
            return "Every mesh now takes its lighting from '" + anchor.name + "' (" + anchored + " changed)" +
                   (fixBounds ? ", and " + bounded + " skinned mesh(es) got bounds that cover the whole avatar." : ".");
        }

        /// <summary>Where the skinned mesh really is right now (its bounds can be smaller than the mesh).</summary>
        private static bool MeshBounds(SkinnedMeshRenderer skinned, out Bounds bounds)
        {
            bounds = new Bounds();
            if (skinned.sharedMesh == null || skinned.sharedMesh.vertexCount == 0)
                return false;

            var baked = new Mesh();
            try
            {
                skinned.BakeMesh(baked, true);
                var vertices = baked.vertices;
                if (vertices.Length == 0)
                    return false;

                // BakeMesh with useScale already applied the scale, so only position and rotation are left to apply.
                var unscaled = Matrix4x4.TRS(skinned.transform.position, skinned.transform.rotation, Vector3.one);
                bounds = new Bounds(unscaled.MultiplyPoint3x4(vertices[0]), Vector3.zero);
                for (int i = 1; i < vertices.Length; i++)
                    bounds.Encapsulate(unscaled.MultiplyPoint3x4(vertices[i]));
                return true;
            }
            finally
            {
                Object.DestroyImmediate(baked);
            }
        }

        private static bool Covers(Bounds outer, Bounds inner)
        {
            var slack = inner.size * 0.02f + Vector3.one * 0.005f;
            return outer.min.x <= inner.min.x + slack.x && outer.min.y <= inner.min.y + slack.y && outer.min.z <= inner.min.z + slack.z &&
                   outer.max.x >= inner.max.x - slack.x && outer.max.y >= inner.max.y - slack.y && outer.max.z >= inner.max.z - slack.z;
        }

        /// <summary>A world-space box as a box in the bone's own space (the eight corners, boxed again).</summary>
        private static Bounds ToLocal(Transform bone, Bounds world)
        {
            var min = world.min;
            var max = world.max;
            var local = new Bounds(bone.InverseTransformPoint(min), Vector3.zero);
            for (int i = 1; i < 8; i++)
            {
                var corner = new Vector3((i & 1) != 0 ? max.x : min.x, (i & 2) != 0 ? max.y : min.y, (i & 4) != 0 ? max.z : min.z);
                local.Encapsulate(bone.InverseTransformPoint(corner));
            }
            return local;
        }
    }

    internal static class WPFMABoundsFixSection
    {
        private const string PrefKey = "WPFMA.Tools.BoundsFixExpanded";

        private static WPFMABoundsFix.State state;
        private static GameObject checkedRoot;
        private static int checkedChoice = -1;
        private static string status;

        internal static void Draw(GUIStyle sectionStyle)
        {
            if (!WPFMAToolSection.AvatarProject)
                return;

            WPFMAToolSection.Draw(sectionStyle, "Bounds & lighting fix", Detail(), PrefKey, Body);
        }

        private static string Detail()
        {
            if (state == null || checkedRoot == null)
                return "select an avatar";
            return state.NeedsFix ? "needs fixing" : "all matching";
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Same lighting and bounds on every mesh.", "Makes every mesh take its lighting from the same bone, so the body and the outfit aren't lit differently, " + "and gives the meshes bounds that cover the whole avatar, so parts don't vanish at some camera angles."), 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;
            }

            int choice = Mathf.Clamp(WPFMAToolDefaults.BoundsAnchor, 0, WPFMABoundsFix.AnchorNames.Length - 1);
            choice = EditorGUILayout.Popup("Lighting follows", choice, WPFMABoundsFix.AnchorNames);
            WPFMAToolDefaults.BoundsAnchor = choice;
            WPFMAToolDefaults.BoundsFixBounds = EditorGUILayout.ToggleLeft("Also fix the bounds", WPFMAToolDefaults.BoundsFixBounds);

            // Checked when the avatar or the bone changes, and on request (it measures every mesh, so not every frame).
            if (state == null || checkedRoot != root || checkedChoice != choice)
            {
                checkedRoot = root;
                checkedChoice = choice;
                state = WPFMABoundsFix.Inspect(root, choice);
            }

            EditorGUILayout.Space(2f);
            EditorGUILayout.LabelField(
                state.Renderers + " mesh(es). " +
                (state.Anchors > 1 || state.WithoutAnchor > 0
                    ? state.Anchors + " different lighting anchor(s)" + (state.WithoutAnchor > 0 ? ", " + state.WithoutAnchor + " with none" : string.Empty) + ". "
                    : "All use the same lighting anchor. ") +
                (state.ShortBounds > 0 ? state.ShortBounds + " skinned mesh(es) have bounds smaller than the mesh." : string.Empty),
                WPFMAToolSection.Hint(state.NeedsFix ? WPFMAToolSection.WarnAmber : WPFMAToolSection.OkGreen));

            using (new EditorGUILayout.HorizontalScope())
            {
                if (GUILayout.Button("Check again", GUILayout.Width(100f), GUILayout.Height(26f)))
                    state = null;
                if (GUILayout.Button("Fix lighting" + (WPFMAToolDefaults.BoundsFixBounds ? " and bounds" : string.Empty), GUILayout.Height(26f)))
                    Fix(root, choice);
            }

            EditorGUILayout.LabelField(new GUIContent("Use the avatar's normal pose.", "Do it with the avatar standing in its normal pose. Undo puts it back."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));

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

        /// <summary>Fixes it on the next editor tick (recorded in the Change log), with the default settings from Settings.</summary>
        internal static void Fix(GameObject root, int choice)
        {
            bool bounds = WPFMAToolDefaults.BoundsFixBounds;
            EditorApplication.delayCall += () =>
            {
                status = WPFMAChangeLog.Run("Bounds & lighting fix", "Fix bounds and lighting on '" + root.name + "'", null, true,
                    () => WPFMABoundsFix.Apply(root, choice, bounds));
                Debug.Log("[WPFMA-SDK] " + status);
                state = null;
            };
        }
    }
}
#endif
