using UnityEditor;
using UnityEngine;

namespace AssetBank.Settings
{
    internal class ProjectExporterSettingsProvider : SettingsProvider
    {
        private SerializedObject m_Settings;
        private SerializedProperty m_FoldersToIgnore;
        private SerializedProperty m_FileExtensionsToIgnore;
        private SerializedProperty m_UnityTypesToIgnore;

        const string k_SettingsPath = "Project/Project AssetDatabase";

        public ProjectExporterSettingsProvider(string path, SettingsScope scope = SettingsScope.Project)
            : base(path, scope) {}

        public override void OnActivate(string searchContext, UnityEngine.UIElements.VisualElement rootElement)
        {
            m_Settings = ProjectExporterSettings.GetSerializedSettings();
            m_FoldersToIgnore = m_Settings.FindProperty("m_FoldersToIgnore");
            m_FileExtensionsToIgnore = m_Settings.FindProperty("m_FileExtensionsToIgnore");
            m_UnityTypesToIgnore = m_Settings.FindProperty("m_UnityTypesToIgnore");
        }

        public override void OnGUI(string searchContext)
        {
            if (m_Settings == null || m_Settings.targetObject == null)
            {
                EditorGUILayout.HelpBox("Settings asset not found. It will be created automatically.", MessageType.Info);
                m_Settings = ProjectExporterSettings.GetSerializedSettings();
                return;
            }
            
            m_Settings.Update();

            EditorGUILayout.PropertyField(m_FoldersToIgnore, new GUIContent("Folders to Ignore"), true);
            EditorGUILayout.PropertyField(m_FileExtensionsToIgnore, new GUIContent("File Extensions to Ignore"), true);
            EditorGUILayout.PropertyField(m_UnityTypesToIgnore, new GUIContent("Unity Types to Ignore"), true);

            if (m_Settings.hasModifiedProperties)
            {
                m_Settings.ApplyModifiedProperties();
            }
        }

        [SettingsProvider]
        public static SettingsProvider CreateSettingsProvider()
        {
            var provider = new ProjectExporterSettingsProvider(k_SettingsPath, SettingsScope.Project);
            provider.keywords = GetSearchKeywordsFromGUIContentProperties<Styles>();
            return provider;
        }

        private class Styles
        {
            public static GUIContent foldersToIgnore = new GUIContent("Folders to Ignore");
            public static GUIContent fileExtensionsToIgnore = new GUIContent("File Extensions to Ignore");
            public static GUIContent unityTypesToIgnore = new GUIContent("Unity Types to Ignore");
        }
    }
}
