using Codice.Client.BaseCommands;
using System;
using System.Collections.Generic;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace ToolsBox.Collider.Editors
{ 
    public static class PopUpTypeEditor
    {
        static string filter = "";

        public static string[] GetMonoBehaviorTypes()
        {
            var monoBehaviourType = typeof(MonoBehaviour);
            var assemblies = AppDomain.CurrentDomain.GetAssemblies();

            List<string> typeNames = new List<string> { "None" };

            foreach (var assembly in assemblies)
            {
                if (assembly.GetName().Name == "Assembly-CSharp")
                {
                    var types = assembly.GetTypes()
                        .Where(t => t.IsSubclassOf(monoBehaviourType) && !t.IsAbstract)
                        .Select(t => t.FullName);

                    typeNames.AddRange(types);
                }
            }
            return typeNames.ToArray();
        }

        public static void PopUp(string[] availableTypes, string propertyName, SerializedObject serializedObject)
        {
            serializedObject.Update();
            EditorGUILayout.LabelField("Types", EditorStyles.boldLabel);

            SerializedProperty typeProperty = serializedObject.FindProperty("_targetTypeName");

            filter = EditorGUILayout.TextField("Filter", filter);
            List<string> filteredType = new List<string>();
            filteredType.Add("None");

            if (!string.IsNullOrEmpty(filter))
            {
                foreach (var type in availableTypes)
                {
                    if (type.ToLower().Contains(filter.ToLower()))
                    {
                        filteredType.Add(type);
                    }
                }
            }
            else
            {
                filteredType.AddRange(availableTypes);
            }

            int index = filteredType.IndexOf(typeProperty.stringValue);

            int newIndex = EditorGUILayout.Popup("typeOf", index, filteredType.ToArray());
            if(newIndex >= 0 && newIndex < filteredType.Count)
            {
                if (newIndex == 0) typeProperty.stringValue = string.Empty;
                else typeProperty.stringValue = filteredType[newIndex];
            }

            serializedObject.ApplyModifiedProperties();

        }
    }
}
