﻿#if UNITY_EDITOR
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using System.Linq;

namespace Onward.CustomContent.EditorTools
{
    public class OnwardOptimizeWindow : EditorWindow
    {
        MeshFilter[] meshesInScene;

        [MenuItem("ONWARD/Optimize Window")]
        static void OptimizeWindow()
        {
            GetWindow<OnwardOptimizeWindow>(false, "Optimize Window", true);
        }

        int totalVerts = 0;

        void OnGUI()
        {
            if (GUILayout.Button("Scan"))
            {
                meshesInScene = FindObjectsOfType<MeshFilter>()
                        .Where(mf => mf != null && mf.sharedMesh != null)
                        .OrderByDescending(mf => mf.sharedMesh.triangles.Length)
                        .ToArray();

                totalVerts = 0;

                for (int i = 0; i < meshesInScene.Length; ++i)
                {
                    MeshFilter m = meshesInScene[i];

                    if (!m.gameObject.activeInHierarchy || m.gameObject.CompareTag("EditorOnly"))
                    {
                        meshesInScene[i] = null;

                        continue;
                    }

                    MeshRenderer mr = m.GetComponent<MeshRenderer>();

                    if (mr == null || !mr.enabled)
                    {
                        meshesInScene[i] = null;

                        continue;
                    }

                    totalVerts += m.sharedMesh.vertices.Length;
                }
            }

            if (meshesInScene == null)
            {
                return;
            }

            GUILayout.Label($"Total active vertices: {totalVerts}");

            GUILayout.Space(25);

            const int Max = 30;

            GUILayout.Label($"Top {Max} highest hitters per vertex count");

            int current = 0;

            for (int i = 0; i < meshesInScene.Length; ++i)
            {
                var mf = meshesInScene[i];

                if (mf == null)
                {
                    continue;
                }

                EditorGUILayout.BeginHorizontal();
                {
                    EditorGUILayout.ObjectField(mf, typeof(MeshFilter), true);
                    GUILayout.Label($"Vertices: {mf.sharedMesh.vertices.Length}");

                    if (GUILayout.Button("Select", GUILayout.Width(100)))
                    {
                        UnityEditor.Selection.activeObject = mf;
                    }
                }
                EditorGUILayout.EndHorizontal();

                ++current;

                if (current >= Max)
                {
                    break;
                }
            }
        }
    }
}
#endif