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

#if WPFMA_VRC_AVATARS
using VRC.SDK3.Avatars.Components;
using VRC.SDKBase.Validation.Performance;
using VRC.SDKBase.Validation.Performance.Stats;
#endif

namespace WPFMA
{
    internal static class WPFMAPerformanceSection
    {
        private const string PrefKey = "WPFMA.Tools.PerformanceExpanded";

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

            WPFMAToolSection.Draw(sectionStyle, "Performance rank", 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 sealed class Row
        {
            public AvatarPerformanceCategory Category;
            public string Label;
            public string Tooltip;
            public PerformanceRating Pc;
            public PerformanceRating Quest;
            public bool Verbose;
        }

        private static VRCAvatarDescriptor checkedAvatar;
        private static List<Row> rows;
        private static PerformanceRating pcOverall;
        private static PerformanceRating questOverall;
        private static string error;
        private static bool onlyProblems { get { return WPFMAToolDefaults.PerformanceOnlyProblems; } set { WPFMAToolDefaults.PerformanceOnlyProblems = value; } }

        private static string Detail()
        {
            if (rows == null || checkedAvatar == null)
                return "not checked yet";

            return "PC " + Name(pcOverall) + "  |  Quest " + Name(questOverall);
        }

        private static void Body()
        {
            var active = Selection.activeGameObject;
            var avatar = active != null && !EditorUtility.IsPersistent(active)
                ? active.GetComponentInParent<VRCAvatarDescriptor>()
                : null;

            EditorGUILayout.LabelField(new GUIContent("PC and Quest rank, and what lowers it.", "Works out the avatar's PC and Quest rank with VRChat's own calculator, and shows what is " + "pulling it down."), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
            EditorGUILayout.Space(4f);

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

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Avatar", avatar.name, EditorStyles.boldLabel);
                if (GUILayout.Button(checkedAvatar == avatar && rows != null ? "Check again" : "Check", GUILayout.Width(110f)))
                {
                    var target = avatar;
                    EditorApplication.delayCall += () => Calculate(target);
                }
            }

            if (!string.IsNullOrEmpty(error))
                EditorGUILayout.LabelField(error, WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));

            if (rows == null || checkedAvatar != avatar)
                return;

            EditorGUILayout.Space(4f);
            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField("Overall", EditorStyles.boldLabel, GUILayout.Width(80f));
                EditorGUILayout.LabelField("PC  " + Name(pcOverall), RatingStyle(pcOverall, true), GUILayout.Width(150f));
                EditorGUILayout.LabelField("Quest  " + Name(questOverall), RatingStyle(questOverall, true));
            }

            if (questOverall == PerformanceRating.VeryPoor)
            {
                EditorGUILayout.LabelField(new GUIContent("Very Poor is hidden on Quest by default.", "Very Poor on Quest means it is hidden by default there - people see a fallback unless they choose to show it."), WPFMAToolSection.Hint(WPFMAToolSection.WarnAmber));
            }

            onlyProblems = EditorGUILayout.ToggleLeft("Only show what lowers the rank", onlyProblems);

            var shown = rows.Where(r => !onlyProblems || Lowers(r))
                .OrderByDescending(r => (int)Worse(r.Pc, r.Quest))
                .ToList();

            if (shown.Count == 0)
            {
                EditorGUILayout.LabelField("Nothing is holding the rank back.", WPFMAToolSection.Hint(WPFMAToolSection.OkGreen));
                return;
            }

            using (new EditorGUILayout.HorizontalScope())
            {
                EditorGUILayout.LabelField(string.Empty, WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
                EditorGUILayout.LabelField("PC", WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(70f));
                EditorGUILayout.LabelField("Quest", WPFMAToolSection.Hint(WPFMAToolSection.FaintText), GUILayout.Width(70f));
                GUILayout.Space(54f);
            }

            foreach (var row in shown)
            {
                using (new EditorGUILayout.HorizontalScope())
                {
                    EditorGUILayout.LabelField(new GUIContent(row.Label, row.Tooltip), WPFMAToolSection.Hint(WPFMAToolSection.MetaText));
                    EditorGUILayout.LabelField(Name(row.Pc), RatingStyle(row.Pc, false), GUILayout.Width(70f));
                    EditorGUILayout.LabelField(Name(row.Quest), RatingStyle(row.Quest, false), GUILayout.Width(70f));

                    var types = Types(row.Category);
                    using (new EditorGUI.DisabledScope(types.Length == 0))
                    {
                        if (GUILayout.Button("Show", EditorStyles.miniButton, GUILayout.Width(50f)))
                            Show(checkedAvatar, types);
                    }
                }
            }

            EditorGUILayout.LabelField(new GUIContent("Hover a row for VRChat's advice.", "Hover a row for VRChat's full advice. The Quest column ranks this same avatar against Quest's limits."), WPFMAToolSection.Hint(WPFMAToolSection.FaintText));
        }

        internal static void Ranks(VRCAvatarDescriptor avatar, out PerformanceRating pc, out PerformanceRating quest)
        {
            pc = Stats(avatar, false).GetPerformanceRatingForCategory(AvatarPerformanceCategory.Overall);
            quest = Stats(avatar, true).GetPerformanceRatingForCategory(AvatarPerformanceCategory.Overall);
        }

        internal static string RatingName(PerformanceRating rating)
        {
            return Name(rating);
        }

        private static void Calculate(VRCAvatarDescriptor avatar)
        {
            error = null;
            rows = null;
            checkedAvatar = avatar;

            if (avatar == null)
                return;

            try
            {
                var pc = Stats(avatar, false);
                var quest = Stats(avatar, true);
                var list = new List<Row>();

                foreach (AvatarPerformanceCategory category in Enum.GetValues(typeof(AvatarPerformanceCategory)))
                {
                    if (category == AvatarPerformanceCategory.Overall ||
                        category == AvatarPerformanceCategory.AvatarPerformanceCategoryCount)
                        continue;

                    string pcText, questText, ignored;
                    PerformanceInfoDisplayLevel pcLevel, questLevel;
                    SDKPerformanceDisplay.GetSDKPerformanceInfoText(pc, category, out pcText, out ignored, out pcLevel);
                    SDKPerformanceDisplay.GetSDKPerformanceInfoText(quest, category, out questText, out ignored, out questLevel);

                    if (pcLevel == PerformanceInfoDisplayLevel.None && questLevel == PerformanceInfoDisplayLevel.None)
                        continue;

                    string text = !string.IsNullOrEmpty(pcText) ? pcText : questText;
                    if (string.IsNullOrEmpty(text))
                        continue;

                    list.Add(new Row
                    {
                        Category = category,
                        Label = ShortLabel(text),
                        Tooltip = text,
                        Pc = pc.GetPerformanceRatingForCategory(category),
                        Quest = quest.GetPerformanceRatingForCategory(category),
                        Verbose = pcLevel == PerformanceInfoDisplayLevel.Verbose && questLevel == PerformanceInfoDisplayLevel.Verbose
                    });
                }

                rows = list;
                pcOverall = pc.GetPerformanceRatingForCategory(AvatarPerformanceCategory.Overall);
                questOverall = quest.GetPerformanceRatingForCategory(AvatarPerformanceCategory.Overall);
            }
            catch (Exception e)
            {
                error = "Could not work out the rank: " + e.Message;
                Debug.LogWarning("[WPFMA-SDK] Performance rank failed: " + e);
            }
        }

        /// <summary>VRChat's own performance numbers for the avatar, on PC or (mobile) Quest.</summary>
        internal static AvatarPerformanceStats StatsFor(VRCAvatarDescriptor avatar, bool mobile)
        {
            return Stats(avatar, mobile);
        }

        private static bool statsReady;

        private static AvatarPerformanceStats Stats(VRCAvatarDescriptor avatar, bool mobile)
        {
            // VRChat loads its rank tables when its control panel starts; until then the calculator fails. Load them ourselves once.
            if (!statsReady)
            {
                AvatarPerformanceStats.Initialize();
                statsReady = true;
            }

            var stats = new AvatarPerformanceStats(mobile);
            AvatarPerformance.CalculatePerformanceStats(avatar.gameObject.name, avatar.gameObject, stats, mobile);
            return stats;
        }

        private static string ShortLabel(string text)
        {
            int cut = text.Length;
            int dash = text.IndexOf(" - ", StringComparison.Ordinal);
            int paren = text.IndexOf(" (", StringComparison.Ordinal);
            if (dash > 0)
                cut = Math.Min(cut, dash);
            if (paren > 0)
                cut = Math.Min(cut, paren);
            return text.Substring(0, cut);
        }

        private static bool Lowers(Row row)
        {
            return (row.Pc > PerformanceRating.Excellent && row.Pc >= pcOverall) ||
                   (row.Quest > PerformanceRating.Excellent && row.Quest >= questOverall) ||
                   row.Pc > PerformanceRating.Medium || row.Quest > PerformanceRating.Medium;
        }

        private static PerformanceRating Worse(PerformanceRating a, PerformanceRating b)
        {
            return (int)a >= (int)b ? a : b;
        }

        private static string Name(PerformanceRating rating)
        {
            return rating == PerformanceRating.VeryPoor ? "Very Poor" : rating.ToString();
        }

        private static GUIStyle RatingStyle(PerformanceRating rating, bool bold)
        {
            Color color;
            switch (rating)
            {
                case PerformanceRating.Excellent:
                case PerformanceRating.Good:
                    color = WPFMAToolSection.OkGreen;
                    break;
                case PerformanceRating.Medium:
                    color = WPFMAToolSection.AccentBlue;
                    break;
                case PerformanceRating.Poor:
                    color = WPFMAToolSection.WarnAmber;
                    break;
                case PerformanceRating.VeryPoor:
                    color = WPFMAToolSection.ErrorRed;
                    break;
                default:
                    color = WPFMAToolSection.FaintText;
                    break;
            }

            var style = new GUIStyle(bold ? EditorStyles.boldLabel : EditorStyles.miniLabel);
            style.normal.textColor = color;
            return style;
        }

        private static Type[] Types(AvatarPerformanceCategory category)
        {
            switch (category)
            {
                case AvatarPerformanceCategory.PolyCount:
                case AvatarPerformanceCategory.MeshCount:
                case AvatarPerformanceCategory.MaterialCount:
                case AvatarPerformanceCategory.TextureMegabytes:
                    return new[] { typeof(MeshRenderer), typeof(SkinnedMeshRenderer) };
                case AvatarPerformanceCategory.SkinnedMeshCount:
                case AvatarPerformanceCategory.BoneCount:
                    return new[] { typeof(SkinnedMeshRenderer) };
                case AvatarPerformanceCategory.PhysBoneComponentCount:
                case AvatarPerformanceCategory.PhysBoneTransformCount:
                    return new[] { typeof(VRC.SDK3.Dynamics.PhysBone.Components.VRCPhysBone) };
                case AvatarPerformanceCategory.PhysBoneColliderCount:
                case AvatarPerformanceCategory.PhysBoneCollisionCheckCount:
                    return new[] { typeof(VRC.SDK3.Dynamics.PhysBone.Components.VRCPhysBoneCollider) };
                case AvatarPerformanceCategory.ContactCount:
                    return new[] { typeof(VRC.Dynamics.ContactBase) };
                case AvatarPerformanceCategory.ConstraintsCount:
                case AvatarPerformanceCategory.ConstraintDepth:
                    return new[] { typeof(VRC.Dynamics.VRCConstraintBase), typeof(UnityEngine.Animations.IConstraint) };
                case AvatarPerformanceCategory.ParticleSystemCount:
                case AvatarPerformanceCategory.ParticleTotalCount:
                case AvatarPerformanceCategory.ParticleMaxMeshPolyCount:
                case AvatarPerformanceCategory.ParticleTrailsEnabled:
                case AvatarPerformanceCategory.ParticleCollisionEnabled:
                    return new[] { typeof(ParticleSystem) };
                case AvatarPerformanceCategory.AudioSourceCount:
                    return new[] { typeof(AudioSource) };
                case AvatarPerformanceCategory.LightCount:
                    return new[] { typeof(Light) };
                case AvatarPerformanceCategory.ClothCount:
                case AvatarPerformanceCategory.ClothMaxVertices:
                    return new[] { typeof(Cloth) };
                case AvatarPerformanceCategory.TrailRendererCount:
                    return new[] { typeof(TrailRenderer) };
                case AvatarPerformanceCategory.LineRendererCount:
                    return new[] { typeof(LineRenderer) };
                case AvatarPerformanceCategory.AnimatorCount:
                    return new[] { typeof(Animator) };
                case AvatarPerformanceCategory.PhysicsRigidbodyCount:
                    return new[] { typeof(Rigidbody) };
                case AvatarPerformanceCategory.PhysicsColliderCount:
                    return new[] { typeof(Collider) };
            }

            return new Type[0];
        }

        private static void Show(VRCAvatarDescriptor avatar, Type[] types)
        {
            if (avatar == null)
                return;

            var found = avatar.GetComponentsInChildren<Component>(true)
                .Where(c => c != null && types.Any(t => t.IsInstanceOfType(c)))
                .Select(c => (UnityEngine.Object)c.gameObject)
                .Distinct()
                .ToArray();

            if (found.Length > 0)
                Selection.objects = found;
        }
#endif
    }
}
#endif
