#if UNITY_EDITOR

using UnityEngine;
using UnityEditor;
using System.IO;
using System;
using System.Collections.Generic;

namespace mgaia.Utils
{
    /// <summary>
    /// Menu utilizado para gerar a database
    /// </summary>
    public class PoolDatabaseEditor : EditorWindow
    {
        /// <summary>
        /// Percorre todos as classes e adiciona todas as que utilizam o atributo sinalizador para o banco de dados
        /// </summary>
        [MenuItem("Pool Manager/Generate pool references")]
        public static void GenerateScriptableObject()
        {
            List<PoolReference> poolReferences = new List<PoolReference>();
            
#if !UNITY_WEBPLAYER
            foreach (string filePath in Directory.GetFiles(Application.dataPath, "*.cs", SearchOption.AllDirectories))
#else
            foreach (string filePath in Directory.GetFiles(Application.dataPath, "*.cs"))
#endif
            {
                string relativeFilePath = Constants.ASSETS_FOLDER_NAME + filePath.Substring(Application.dataPath.Length);

                MonoScript classMonoScript = (MonoScript)AssetDatabase.LoadAssetAtPath(relativeFilePath, typeof(MonoScript));

                if (classMonoScript != null)
                {
                    Type classType = classMonoScript.GetClass();

                    if (classType != null)
                    {
                        object[] poolElementDescriptors = classType.GetCustomAttributes(typeof(PoolElementDescriptorAttribute), false);
                        if (poolElementDescriptors != null && poolElementDescriptors.Length > 0)
                        {
                            PoolElementDescriptorAttribute poolElementDescriptor = (PoolElementDescriptorAttribute)poolElementDescriptors.First();

                            string alias;

                            if (poolElementDescriptor.HasAlias)
                            {
                                alias = poolElementDescriptor.Alias;
                            }
                            else
                            {
                                alias = classMonoScript.name;
                            }

                            poolReferences.Add(new PoolReference { Path = poolElementDescriptor.Path, Quantity = poolElementDescriptor.Quantity, Alias = alias });
                        }
                    }
                }
            }

            PoolDatabaseScriptableObject poolDatabase = new PoolDatabaseScriptableObject();
            poolDatabase.PoolElementsReferences = poolReferences.ToArray();

            string databasePath = PoolDatabase.GetPathForDatabase();

            AssetDatabase.DeleteAsset(databasePath);
            AssetDatabase.CreateAsset(poolDatabase, databasePath);
        }
    }
}

#endif