using UnityEditor;
using UnityEditor.Presets;

namespace XGame.Editor.Asset.Processor
{
    public partial class AssetsConfig
    {
        private static AssetsConfig _instance;

        private static AssetsConfig Instance
        {
            get
            {
                if (_instance == null)
                {
                    var assetPath = PathDefine.AssetsConfigPath;
                    _instance = AssetDatabase.LoadAssetAtPath<AssetsConfig>(assetPath);
                    if (_instance == null)
                    {
                        if (System.IO.File.Exists(assetPath))
                        {
                            return null;
                        }
                        if (!System.IO.Directory.Exists(PathDefine.AssetsEditor))
                        {
                            System.IO.Directory.CreateDirectory(PathDefine.AssetsEditor);
                        }
                        _instance = CreateInstance<AssetsConfig>();
                        var guids = AssetDatabase.FindAssets("AssetsConfigTemplate");
                        if (guids.Length > 0)
                        {
                            var templatePath = AssetDatabase.GUIDToAssetPath(guids[0]);
                            var preset = AssetDatabase.LoadAssetAtPath<Preset>(templatePath);
                            preset.ApplyTo(_instance);
                        }
                        else
                        {
                            _instance.atlasInfo = AtlasInfo.DefaultInfo();
                            _instance.importHandle = AssetsImportHandle.Default();
                        }
                        AssetDatabase.CreateAsset(_instance, PathDefine.AssetsConfigPath);
                        AssetDatabase.SaveAssets();
                        AssetDatabase.Refresh();
                    }
                }
                return _instance;
            }
        }
        #region 图集
        public static int AtlasLayerLimit => Instance.atlasInfo.atlasLayerLimit;
        public static SpritePackerMode PackerMode => Instance.atlasInfo.packerMode;
        public static Preset SpriteAtlasPreset => Instance.atlasInfo.spriteAtlasPreset;
        public static int AtlasNameType => Instance.atlasInfo.atlasNameType;
        #endregion

        #region 资源导入
        /// <summary>
        /// 导入操作器
        /// </summary>
        public static IAssetsImportHandle ImportHandle => Instance.importHandle;
        #endregion
        public static void GenPreset()
        {
            var instance = Instance;
        }
        public static void ClearCache()
        {
            _instance = null;
        }
        //[MenuItem("Tools/LoadAssetsConfig")]
        //public static void Test()
        //{
        //    var temp = Instance;
        //    ClearCache();
        //}
    }

}