using XGame.Framework.Define;
using System.IO;
using UnityEditor;
using UnityEngine;
using XGame.Framework;

namespace XGame.Editor.Asset.Processor
{
    public static class PostprocessorGenerator
    {
        [MenuItem("Tools/XGame/创建资源导入脚本")]
        public static void GenAssetPostprocessor()
        {
            var guids = AssetDatabase.FindAssets("AssetPostprocessorTemplate");
            if (guids.Length > 0)
            {
                var assetPath = AssetDatabase.GUIDToAssetPath(guids[0]);
                var txtAsset = AssetDatabase.LoadAssetAtPath<TextAsset>(assetPath);
                if (txtAsset != null)
                {
                    var xConfig = AddressableHelper.LoadAssetByName<XGameConfig>(AssetDefine.XGAME_CONFIG_NAME);
                    var productName = xConfig?.productName ?? "Demo";
                    var processorTxt = txtAsset.text.Replace("#ProductName#", productName);
                    var outputPath = PathDefine.AssetsEditor;
                    if (!Directory.Exists(outputPath))
                    {
                        Directory.CreateDirectory(outputPath);
                    }
                    outputPath = Path.Combine(outputPath, "XAssetPostprocessor.cs");
                    File.WriteAllText(outputPath, processorTxt);
                    AssetDatabase.Refresh();
                }
            }
            else
            {
                Debug.LogError("没有找到 AssetPostprocessorTemplate");
            }
            AssetsConfig.GenPreset();
        }
    }
}

