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

namespace Jovian.Logger {
    internal sealed class LoggerSettingsProvider : SettingsProvider {
        public LoggerSettingsProvider(string path, SettingsScope scopes, IEnumerable<string> keywords = null) : base(path, scopes, keywords) { }

        public const string SETTINGS_FILE = "Assets/Settings/Resources/logger-settings.asset";

        [SettingsProvider]
        public static SettingsProvider CreateSettingsProvider() {
            var provider = new SettingsProvider("Project/Jovian/Logger", SettingsScope.Project) {
                guiHandler = (searchContext) => { LoggerSettingsEditor.ShowSettings(); }
            };
            return provider;
        }

        private class ConfigLoader : AssetPostprocessor {
            private static AssetSettingsLoader<LoggerSettings> loader;

            private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths) {
                loader ??= new AssetSettingsLoader<LoggerSettings>();
                loader.GetSettings(SETTINGS_FILE);
            }
        }
    }

    public class AssetSettingsLoader<T> where T : ScriptableObject {
        private T settings;

        /// <summary>
        /// Get the settings file if cached/existent. If it doesn't exist, it will create one.
        /// </summary>
        /// <param name="settingsFilePath"></param>
        /// <returns></returns>
        public T GetSettings(string settingsFilePath) {
            return settings ?? SetSettings(settingsFilePath);
        }

        private T SetSettings(string settingsFilePath) {
            if(!Directory.Exists(Path.GetDirectoryName(settingsFilePath))) {
                Directory.CreateDirectory(Path.GetDirectoryName(settingsFilePath));
            }

            settings = AssetDatabase.LoadAssetAtPath<T>(settingsFilePath);
            if(settings != null) {
                return settings;
            }

            settings = ScriptableObject.CreateInstance<T>();
            AssetDatabase.CreateAsset(settings, settingsFilePath);
            AssetDatabase.SaveAssets();

            settings = AssetDatabase.LoadAssetAtPath<T>(settingsFilePath);
            return settings;
        }
    }
}
