using XGame.Editor.Asset;
using System.Diagnostics;
using UnityEditor;

namespace XGame.Editor.Build
{
    internal class LocalizedBuild
    {

        /// <summary>
        /// 只打包apk，不做其他事
        /// </summary>
        internal static void BuildPlayer()
        {
            var buildTarget = EditorUserBuildSettings.activeBuildTarget;
            var outputPath = PathDefine.DefaultOutputPath;
            var config = new BuildConfig()
            {
                target = buildTarget,
                callback = BuildUtils.CallbackToString(BuildCallback),
            };
            config.project = new BuildConfig.ProjectSettings()
            {
                bundleVersion = PlayerSettings.bundleVersion,
                productName = PlayerSettings.productName,
                outputPath = outputPath,
            };
            config.android.exportAsGoogleAndroidProject = EditorUserBuildSettings.exportAsGoogleAndroidProject;
            config.editor.autoExplorer = buildTarget != BuildTarget.iOS;
            BuildPlayer(config);
        }

        internal static void BuildPlayer(BuildConfig config)
        {
            var builder = new ContextBuilder(config, false);
            if (builder.Build())
            {
                var context = builder.GetProduct();
                BuildLog.Log($"LocalizedBuild BuildPlayer begin.");
                //开始计时
                Stopwatch stopwatch = new Stopwatch();
                stopwatch.Start();
                //执行命令
                IBuildCommand cmd = new CmdBuildPlayer();
                if (cmd is IBuildContextAdapter adapter)
                {
                    adapter.Context = context;
                }
                cmd.Start();
                //结束
                stopwatch.Stop();
                BuildLog.Log($"LocalizedBuild BuildPlayer Completed. Esapsed Time: {stopwatch.ElapsedMilliseconds} ms.");
            }

        }

        private static void BuildCallback(int code)
        {
            BuildLog.Log($"LocalizedBuild BuildCallback code:{code}");
        }
    }
}
