using XGame.Editor.Compiler;
using System.IO;
using XGame.Framework.Json;

namespace XGame.Editor.Build
{
    /// <summary>
    /// 命令行打包
    /// </summary>
    public class CommandLineBuild
    {
        public static void BuildApp()
        {
            var configPath = BuildUtils.GetCommandLineArgs();
            //var configPath = PathDefine.ExtAssetsPath + "/Editor/BuildConfig.json";
            if (string.IsNullOrEmpty(configPath) || !File.Exists(configPath))
            {
                BuildLog.Error($"Can't Find BuildConfig.json. Path:{configPath}");
                UnityEditor.EditorApplication.Exit((int)BuildErrorCode.ConfigFileMissing);
                return;
            }
            var configStr = File.ReadAllText(configPath);
            var config = XJson.ToObject<BuildConfig>(configStr);
            BuildApp(config);
        }
        public static void BuildApp(BuildConfig config)
        {
            BuildLog.Log($"CommandLineBuild BuildApp Start. Target:{config.target} publish:{config.publishType} isSetScriptDefine:{config.isSetScriptDefine}" +
                $" ignoreGenIlrt:{config.project.isIgnoreGenIlrt}");
            var builder = new ContextBuilder(config, true);
            if (builder.Build())
            {
                var context = builder.GetProduct();
                CompileScriptsHandle.Clear();
                var cmd = CmdFactory.Create(context);
                cmd.Start();
            }
        }
    }
}
