using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using NBC.Asset.Editor;
using UnityEditor;
using Debug = UnityEngine.Debug;

namespace NBF
{
    /// <summary>
    /// 打包器
    /// </summary>
    public class Builder
    {
        /// <summary>
        /// 任务id对应的类型
        /// </summary>
        private static readonly Dictionary<int, Type> _buildTaskTypes = new Dictionary<int, Type>();

        /// <summary>
        /// 任务配置信息
        /// </summary>
        public static readonly List<BuildTaskInfoAttribute> BuildTaskInfo = new List<BuildTaskInfoAttribute>();


        [InitializeOnLoadMethod]
        private static void OnInitialize()
        {
            FindTasks();
        }

        private static void FindTasks()
        {
            var types = EditUtil.FindAllSubclass<BaseBuildTask>();
            foreach (var t in types)
            {
                var attributes = t.GetCustomAttributes(typeof(BuildTaskInfoAttribute), true);
                foreach (var attribute in attributes)
                {
                    if (attribute is BuildTaskInfoAttribute idAttribute && idAttribute.Id > 0)
                    {
                        _buildTaskTypes[idAttribute.Id] = t;
                        BuildTaskInfo.Add(idAttribute);
                    }
                }
            }

            BuildTaskInfo.Sort((a, b) => a.Id - b.Id);
        }

        private static Type GetTaskType(int id)
        {
            return _buildTaskTypes.GetValueOrDefault(id);
        }


        #region 对外公共方法

        /// <summary>
        /// 供cmd调用的打包接口
        /// </summary>
        /// <exception cref="Exception"></exception>
        public static void RunBuild()
        {
            var ver = string.Empty;
            var ding = 0;
            List<int> ids = new List<int>();

            List<string> systemValue = new List<string>(Environment.GetCommandLineArgs());
            foreach (var str in systemValue)
            {
                var arr = str.Split("=");
                if (arr.Length > 1)
                {
                    var key = arr[0];
                    var value = arr[1];

                    if (key == "v")
                    {
                        ver = value;
                    }
                    else if (key == "ids")
                    {
                        var idArr = value.Split(',');
                        if (idArr.Length > 0)
                        {
                            foreach (var id in idArr)
                            {
                                if (int.TryParse(id, out var i) && i > 0)
                                {
                                    ids.Add(i);
                                }
                            }
                        }
                    }
                }
            }

            if (string.IsNullOrEmpty(ver) || ids.Count < 1)
            {
                throw new Exception("参数错误");
            }

            BuildContext buildContext = new BuildContext
            {
                Ver = ver
            };

            RunBuildTasks(buildContext, ids.ToArray());
        }

        public static void RunBuildTasks(BuildContext buildContext, params int[] ids)
        {
            Debug.Log("开始执行构建任务");

            List<Type> types = ids.Select(GetTaskType).Where(type => type != null).ToList();
            if (types.Count < 1)
            {
                throw new Exception("task id error!");
            }

            List<BaseBuildTask> buildTasks = new List<BaseBuildTask>();
            foreach (var type in types)
            {
                if (Activator.CreateInstance(type) is BaseBuildTask task)
                {
                    buildTasks.Add(task);
                }
            }

            foreach (var task in buildTasks)
            {
                var sw = new Stopwatch();
                sw.Start();
                task.Run(buildContext);
                sw.Stop();
                Debug.Log($"Run 任务={task.GetType().Name} time={sw.ElapsedMilliseconds / 1000f}s");
            }
        }

        #endregion


        public static BuildTargetGroup GetTargetGroup()
        {
            BuildTarget activeTarget = EditorUserBuildSettings.activeBuildTarget;
            var targetGroup = BuildTargetGroup.Unknown;

            if (activeTarget == BuildTarget.StandaloneWindows || activeTarget == BuildTarget.StandaloneWindows64)
            {
                targetGroup = BuildTargetGroup.Standalone;
            }
            else if (activeTarget == BuildTarget.Android)
            {
                targetGroup = BuildTargetGroup.Android;
            }
            else if (activeTarget == BuildTarget.iOS)
            {
                targetGroup = BuildTargetGroup.iOS;
            }

            return targetGroup;
        }
    }
}