using System;
using System.IO;
using System.Linq;
using UnityEditor;
using UnityEngine;

namespace NBF
{
    /// <summary>
    /// 打包app
    /// </summary>
    [BuildTaskInfo(BuildTaskId.App, "打包App")]
    public class BuildAppTask : BaseBuildTask
    {
        public static readonly string AppInfoPath = Application.dataPath + "/Scripts/Def/AppInfo.cs";
        public static readonly string ProjectDir = Directory.GetParent(Application.dataPath)?.ToString();


        private BuildContext _context;

        public override void Run(BuildContext context)
        {
            _context = context;
            ChangeAppInfo();
            BuildAppByPath();
        }

        /// <summary>
        /// 修改打包脚本信息
        /// </summary>
        private void ChangeAppInfo()
        {
            if (!File.Exists(AppInfoPath))
            {
                Debug.LogError("app info 脚本路径错误");
                return;
            }

            EditorUserBuildSettings.exportAsGoogleAndroidProject = false;

            if (_context.Ver != PlayerSettings.bundleVersion)
            {
                PlayerSettings.bundleVersion = _context.Ver;
            }

            var change = false;
            var lines = File.ReadAllLines(AppInfoPath);
            for (var i = 0; i < lines.Length; i++)
            {
                var str = lines[i];
                if (str.Contains("string Code"))
                {
                    if (!str.Contains(_context.Ver))
                    {
                        lines[i] = $"\t\tpublic const string Code = \"{_context.Ver}\";";
                        change = true;
                    }
                }
            }

            if (change)
            {
                File.WriteAllLines(AppInfoPath, lines);
                AssetDatabase.Refresh();
            }
        }

        private void BuildAppByPath()
        {
            // 设置打包的输出路径
            string outputPath = $"{ProjectDir}/Release";

            string location =
                $"{outputPath}/{_context.Ver}/Fishing.exe";
            BuildTarget activeTarget = EditorUserBuildSettings.activeBuildTarget;

            switch (activeTarget)
            {
                case BuildTarget.StandaloneWindows:
                case BuildTarget.StandaloneWindows64:
                case BuildTarget.Android:
                case BuildTarget.iOS:
                    EditorSettings.spritePackerMode = SpritePackerMode.AlwaysOnAtlas;
                    PlayerSettings.gcIncremental = true;
                    break;
            }

            var targetGroup = Builder.GetTargetGroup();
            if (targetGroup == BuildTargetGroup.Unknown)
            {
                Debug.LogError("不支持的平台");
                return;
            }

            // 读取 Build Settings 中 “Scenes In Build” 勾选的场景
            var scenes = EditorBuildSettings.scenes
                .Where(s => s.enabled)
                .Select(s => s.path)
                .ToArray();
            var buildOptions = BuildOptions.CompressWithLz4;
            BuildPlayerOptions buildPlayerOptions = new BuildPlayerOptions()
            {
                scenes = scenes, //new[] { "Assets/Scenes/StartUp.unity" }, //Assets/Scenes/StartUp.unity
                locationPathName = location,
                options = buildOptions,
                target = activeTarget,
                targetGroup = targetGroup,
            };

            var report = BuildPipeline.BuildPlayer(buildPlayerOptions);
            if (report.summary.result != UnityEditor.Build.Reporting.BuildResult.Succeeded)
            {
                Debug.LogError("打包失败");
                return;
            }
#if UNITY_EDITOR
            Application.OpenURL($"file:///{outputPath}");
#endif
        }
    }
}