using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using XGame.Framework;

namespace XGame.Editor.Build
{
    [BuildCommand((uint)BuildCommandPriority.SetScriptingDefine)]
    class CmdSetScriptingDefine : BaseBuildCommand, ICommandExecuterAsync
    {
        public void Execute()
        {
            BuildLog.Log("CmdSetScriptingDefine Execute.");
            if (!Context.config.isSetScriptDefine)
            {
                //不设置宏
                this.Completed();
                return;
            }
            var targetGroup = Context.config.target.ToTargetGroup();
            // 预编译宏<宏名字，是否增加>
            var macroMap = new Dictionary<string, bool>();
            var publishType = Context.config.publishType;
            macroMap.Add(MacroDefine.DEBUG, publishType == PublishType.Debug);
            macroMap.Add(MacroDefine.PROFILER, publishType == PublishType.Profiler);
            macroMap.Add(MacroDefine.FINAL_RELEASE, publishType != PublishType.Debug);
            //UPR开关宏
            macroMap.Add("NO_PACKAGE", publishType != PublishType.Profiler);

            var sdList = new List<string>();
            //先取PlaySettings的预编译宏
            var lastSD = PlayerSettings.GetScriptingDefineSymbolsForGroup(targetGroup);
            if (!string.IsNullOrEmpty(lastSD))
            {
                var sds = lastSD.Split(';');
                foreach (var sd in sds)
                {
                    if (!string.IsNullOrEmpty(sd))
                    {
                        sdList.Add(sd);
                    }
                }
            }
            //根据发布版本增/减预编译宏
            var change = false;
            foreach (var macro in macroMap)
            {
                var sd = macro.Key;
                var isAdd = macro.Value;
                if (sdList.Contains(sd))
                {
                    if (!isAdd)
                    {
                        sdList.Remove(sd);
                        change = true;
                    }
                }
                else
                {
                    if (isAdd)
                    {
                        sdList.Add(sd);
                        change = true;
                    }
                }
            }

            if (change)
            {
                BuildCompileEvent.RegistEvent(Context);
                var nextSD = string.Join(";", sdList);

                BuildLog.Log($"SetScriptingDefine: {nextSD}");
                PlayerSettings.SetScriptingDefineSymbolsForGroup(targetGroup, nextSD);
                return;
                //AssetDatabase.SaveAssets();
                //AssetDatabase.Refresh();
                //打包机没启动编辑器界面，不会主动保存配置，强制重新编译脚本以保存配置
                //UnityEditor.Compilation.CompilationPipeline.RequestScriptCompilation();
            }
            this.Completed();
        }
    }
}
