// 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>
    /// Triangles, vertices and materials of whatever is selected (children included), and which parts of it are
    /// the heaviest. Updates as the selection changes.
    /// </summary>
    internal static class WPFMATriangleCounterSection
    {
        private const string PrefKey = "WPFMA.Tools.TriangleCounterExpanded";
        private const string ChildrenKey = "WPFMA.Tools.TriangleCounter.Children";
        private const string InactiveKey = "WPFMA.Tools.TriangleCounter.Inactive";
        private const int TopCount = 8;

        private sealed class Part
        {
            public Renderer Renderer;
            public long Triangles;
            public int Vertices;
        }

        private sealed class Count
        {
            public int Objects;
            public long Triangles;
            public long Vertices;
            public int Meshes;
            public int Skinned;
            public int Materials;
            public int MaterialSlots;
            public readonly List<Part> Parts = new List<Part>();
        }

        private static Count count;
        private static int countedFor = -1;
        private static bool changed = true;

        // Counted again only when something changes, not every second while the Tools page is open.
        static WPFMATriangleCounterSection()
        {
            Selection.selectionChanged += () => changed = true;
            EditorApplication.hierarchyChanged += () => changed = true;
            Undo.undoRedoPerformed += () => changed = true;
            ObjectChangeEvents.changesPublished += (ref ObjectChangeEventStream stream) => changed = true;
        }

        internal static void Draw(GUIStyle sectionStyle)
        {
            Refresh();
            string detail = count == null ? "select something" : count.Triangles.ToString("N0") + " triangles selected";
            WPFMAToolSection.Draw(sectionStyle, "Triangle counter", detail, PrefKey, Body);
        }

        internal static bool Children
        {
            get { return EditorPrefs.GetBool(ChildrenKey, true); }
            set { EditorPrefs.SetBool(ChildrenKey, value); }
        }

        internal static bool Inactive
        {
            get { return EditorPrefs.GetBool(InactiveKey, false); }
            set { EditorPrefs.SetBool(InactiveKey, value); }
        }

        private static void Body()
        {
            EditorGUILayout.LabelField(new GUIContent("Select objects to count triangles.", "Select objects in the Hierarchy to see how many triangles and vertices they have, and which parts are the heaviest."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

            using (new EditorGUILayout.HorizontalScope())
            {
                bool children = EditorGUILayout.ToggleLeft("Include children", Children, GUILayout.Width(140f));
                bool inactive = EditorGUILayout.ToggleLeft("Include hidden objects", Inactive);
                if (children != Children || inactive != Inactive)
                {
                    Children = children;
                    Inactive = inactive;
                    countedFor = -1;
                    Refresh();
                }
            }

            if (count == null)
            {
                EditorGUILayout.LabelField("Nothing selected in the scene.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                return;
            }

            EditorGUILayout.Space(2f);
            Row("Triangles", count.Triangles.ToString("N0"), WPFMAToolSection.AccentBlue);
            Row("Vertices", count.Vertices.ToString("N0"), WPFMAToolSection.MetaText);
            Row("Meshes", count.Meshes + (count.Skinned > 0 ? " (" + count.Skinned + " skinned)" : string.Empty), WPFMAToolSection.MetaText);
            Row("Materials", count.Materials + " different, " + count.MaterialSlots + " slots", WPFMAToolSection.MetaText);
            Row("Objects", count.Objects.ToString("N0"), WPFMAToolSection.MetaText);

            if (count.Parts.Count > 1)
            {
                EditorGUILayout.Space(4f);
                EditorGUILayout.LabelField("Heaviest parts", EditorStyles.boldLabel);
                foreach (var part in count.Parts.Take(TopCount))
                {
                    if (part.Renderer == null)
                        continue;
                    float share = count.Triangles > 0 ? (float)part.Triangles / count.Triangles : 0f;
                    using (new EditorGUILayout.HorizontalScope())
                    {
                        EditorGUILayout.LabelField(part.Renderer.name, GUILayout.MinWidth(80f));
                        EditorGUILayout.LabelField(part.Triangles.ToString("N0") + "  (" + Mathf.RoundToInt(share * 100f) + "%)",
                            WPFMAToolSection.Hint(share >= 0.5f ? WPFMAToolSection.WarnAmber : WPFMAToolSection.MetaText), GUILayout.Width(120f));
                        if (GUILayout.Button("Select", EditorStyles.miniButton, GUILayout.Width(50f)))
                        {
                            Selection.activeObject = part.Renderer.gameObject;
                            EditorGUIUtility.PingObject(part.Renderer.gameObject);
                        }
                    }
                }
                if (count.Parts.Count > TopCount)
                    EditorGUILayout.LabelField("and " + (count.Parts.Count - TopCount) + " more.", WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
            }

            EditorGUILayout.Space(2f);
            EditorGUILayout.LabelField(new GUIContent("Counts every LOD.", "Counts every LOD level, and a mesh used twice counts twice (that's what gets drawn)."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
        }

        private static void Row(string label, string value, Color color)
        {
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(label, GUILayout.Width(90f));
                EditorGUILayout.LabelField(value, WPFMAToolSection.Hint(color));
            }
        }

        /// <summary>Counts again only when the selection (or what's in it) changed.</summary>
        private static void Refresh()
        {
            var selected = Selection.gameObjects.Where(g => g != null && g.scene.IsValid()).ToArray();
            int key = 17;
            unchecked
            {
                foreach (var go in selected)
                    key = key * 31 + go.GetInstanceID();
                key = key * 31 + (Children ? 1 : 0) + (Inactive ? 2 : 0);
            }
            if (key == countedFor && !changed)
                return;
            countedFor = key;
            changed = false;
            count = selected.Length == 0 ? null : Measure(selected);
        }

        private static Count Measure(GameObject[] selected)
        {
            var result = new Count();
            var renderers = new HashSet<Renderer>();
            var objects = new HashSet<GameObject>();
            foreach (var go in selected)
            {
                IEnumerable<Renderer> found = Children ? go.GetComponentsInChildren<Renderer>(true) : go.GetComponents<Renderer>();
                foreach (var renderer in found)
                    if (Inactive || (renderer.enabled && renderer.gameObject.activeInHierarchy))
                        renderers.Add(renderer);
                if (Children)
                    foreach (var t in go.GetComponentsInChildren<Transform>(true))
                    {
                        if (Inactive || t.gameObject.activeInHierarchy)
                            objects.Add(t.gameObject);
                    }
                else
                    objects.Add(go);
            }

            var materials = new HashSet<Material>();
            foreach (var renderer in renderers)
            {
                Mesh mesh = null;
                var skinned = renderer as SkinnedMeshRenderer;
                if (skinned != null)
                {
                    mesh = skinned.sharedMesh;
                    if (mesh != null)
                        result.Skinned++;
                }
                else if (renderer is MeshRenderer)
                {
                    var filter = renderer.GetComponent<MeshFilter>();
                    mesh = filter != null ? filter.sharedMesh : null;
                }
                if (mesh == null)
                    continue;

                long triangles = Triangles(mesh);
                result.Meshes++;
                result.Triangles += triangles;
                result.Vertices += mesh.vertexCount;
                result.MaterialSlots += renderer.sharedMaterials.Length;
                foreach (var material in renderer.sharedMaterials)
                    if (material != null)
                        materials.Add(material);
                result.Parts.Add(new Part { Renderer = renderer, Triangles = triangles, Vertices = mesh.vertexCount });
            }

            result.Objects = objects.Count;
            result.Materials = materials.Count;
            result.Parts.Sort((a, b) => b.Triangles.CompareTo(a.Triangles));
            return result;
        }

        internal static long Triangles(Mesh mesh)
        {
            long triangles = 0;
            for (int i = 0; i < mesh.subMeshCount; i++)
            {
                var topology = mesh.GetTopology(i);
                long indices = mesh.GetIndexCount(i);
                if (topology == MeshTopology.Triangles)
                    triangles += indices / 3;
                else if (topology == MeshTopology.Quads)
                    triangles += indices / 4 * 2;
            }
            return triangles;
        }
    }
}
#endif
