using UnityEditor;
using UnityEditor.Presets;

namespace XGame.Editor.Asset.Processor
{
    public abstract class AssetImportOption<TImporter> where TImporter : AssetImporter
    {
        public string[] importKeys;
        public Preset preset;

        public bool TryApplyImporter(string assetPath, TImporter importer)
        {
            if (preset == null) return false;
            if (importKeys == null || importKeys.Length == 0)
            {
                //没有key则表示该预设是通用的，所有同类型Importer共用
                PreApplyImporter(assetPath, importer);
                preset.ApplyTo(importer);
                OnApplyImporter(assetPath, importer);
                return true;
            }
            foreach(var key in importKeys)
            {
                if (assetPath.Contains(key))
                {
                    PreApplyImporter(assetPath, importer);
                    preset.ApplyTo(importer);
                    OnApplyImporter(assetPath, importer);
                    return true;
                }
            }
            return false;
        }
        private void Init()
        {
            var guids = AssetDatabase.FindAssets(PresetTemplateName);
            if (guids.Length > 0)
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(guids[0]);
                preset = AssetDatabase.LoadAssetAtPath<Preset>(assetPath);
            }
            OnInit();
        }
        protected abstract string PresetTemplateName { get; }
        protected abstract void OnInit();
        protected abstract void PreApplyImporter(string assetPath, TImporter importer);
        protected abstract void OnApplyImporter(string assetPath, TImporter importer);


        public static TOption Create<TOption>() where TOption : AssetImportOption<TImporter>, new()
        {
            TOption _t = new TOption();
            _t.Init();
            return _t;
        }
    }
}
