using System;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace XGame.Editor.Build
{
    internal static class BuildUtils
    {
        /// <summary>
        /// 回调函数必须是静态的
        /// </summary>
        /// <param name="callback"></param>
        /// <returns></returns>
        public static string CallbackToString(Action<int> callback)
        {
            return  $"<callback type:{callback.Method.ReflectedType.AssemblyQualifiedName} method:{callback.Method.Name} /callback>";
        }
        public static string GetCommandLineArgs()
        {
            string[] args = Environment.GetCommandLineArgs();
            int index = args.ToList().IndexOf("--args");
            if (index >= args.Length) return string.Empty;
            string res = args[index + 1];
            if (res[0] == '-' || res.IndexOf("--") == 0) return string.Empty;
            return res;
        }
        public static void CmdCompleted(BuildErrorCode code, BuildContext context)
        {
            BuildLog.Log($"CmdCompleted. Code:{code}");
            if (code == BuildErrorCode.CmdCompleted)
            {
                var cmd = CmdFactory.Create(context);
                if (cmd != null)
                {
                    // 还有Cmd接着执行
                    cmd.Start();
                    return;
                }
                else
                {
                    //结束
                    code = BuildErrorCode.Succeeded;
                }
            }
            else
            {
                BuildLog.Warn($"Build Completed. Code:{code}");
            }
            BuildCompleted(context.config.callback, code);
            BuildLog.Log($"context.config.editor.autoExit: {context.config.editor.autoExit}");
            if (context.config.editor.autoExit)
            {
                ExitApplication(code);
            }
        }

        public static void BuildCompleted(string callback, BuildErrorCode code)
        {
            BuildLog.Log($"OnBuildCompleted. callback:{callback} code:{code}");
            if (string.IsNullOrEmpty(callback) == false)
            {
                try
                {
                    Regex regex = new Regex(@"<callback type:(.+?) method:(.+?) /callback>", RegexOptions.Multiline);
                    var match = regex.Match(callback);
                    if (match.Success)
                    {
                        var typeName = match.Groups[1].Value;
                        var methodName = match.Groups[2].Value;
                        Type type = Type.GetType(typeName);
                        var methodInfo = type.GetMethod(methodName, BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static);
                        methodInfo?.Invoke(null, new object[] { (int)code });
                    }
                }
                catch (Exception ex)
                {
                    BuildLog.Exception(ex);
                }
            }
        }
        public static void ExitApplication(BuildErrorCode code)
        {
            UnityEditor.EditorApplication.Exit(ErrorCodeToInt(code));
        }
        private static int ErrorCodeToInt(BuildErrorCode code)
        {
            switch (code)
            {
                case BuildErrorCode.Succeeded:
                    return 0;
                case BuildErrorCode.Unknown:
                    return 1;
                default:
                    return (int)code;
            }
        }
    }
}
