using System;
using System.Collections.Generic;
using System.Linq;
using Alphaleonis.Win32.Filesystem;
using UnityEditor;
using UnityEditor.Build;
using UnityEditor.Build.Reporting;
using UnityEngine;

namespace TyphoonUnitySDK
{
    public class PublishMiniGame : IPublish
    {
        private static Action NextStep { get; set; }

        private void ExecutePublish(PublishSetting setting)
        {
            PublishResult result = new PublishResult();
            //导出到指定目录
            var path = $".typhoonoutput/minigame{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            result.MiniGameProj = path;
            UniEditor.CreateDirIfNotExist(Path.GetDirectoryName(path));
            if (!UniEditor.IsAsciiPath(path))
            {
                UniEditor.ShowMessageBox($"路径不符合要求，不支持中文路径：\n当前：{path}", null);
                return;
            }

            PublishTool.InvokeOnPublishStart(setting);
            //导出前执行
            var report =
                BuildPipeline.BuildPlayer(EditorBuildSettings.scenes, path, BuildTarget.WebGL, BuildOptions.None);
            if (report.summary.result != BuildResult.Succeeded)
            {
                var errors = new List<string>();
                foreach (var step in report.steps)
                {
                    foreach (var msg in step.messages)
                    {
                        if (msg.type == LogType.Error || msg.type == LogType.Exception)
                        {
                            errors.Add(msg.content);
                        }
                    }
                }

                if (errors.Count > 0)
                {
                    var outRangeException = errors.Last().Contains("IndexOutOfRangeException");
                    if (outRangeException)
                    {
                        UniEditor.ShowMessageBox(
                            $"发布失败：IndexOutOfRangeException: Index was outside the bounds of the array.\n\n请手动再选择一下WebGL模板为 MiniGame 后再发布\n\n去设置？",
                            () => SettingsService.OpenProjectSettings());
                    }
                }

                throw new Exception($"发布失败!");
            }

            if (!Directory.Exists(path))
            {
                throw new Exception($"发布失败！找不到：{path}");
            }

            var indexFile = $"{path}/index.html";
            if (!File.Exists(indexFile))
            {
                throw new Exception($"发布失败！找不到：{indexFile}");
            }

            Debug.Log($"发布成功！目录：{path}");
            EditorUtility.RevealInFinder(indexFile);
            result.IsSuccess = true;
            PublishTool.InvokeOnPublishEnd(setting, result);
        }

        private void OnEditorUpdate()
        {
            AssetDatabase.Refresh();
            AssetDatabase.SaveAssets();
            EditorApplication.delayCall -= OnEditorUpdate;
            UniEditor.ShowMessageBox("WEBGL模板更新完毕\n继续打包？", () => { NextStep?.Invoke(); });
        }

        public void Publish(PublishSetting setting)
        {
            //PlayerSettingDefaultOpened=
            SettingsService.OpenProjectSettings();
            NextStep = () => ExecutePublish(setting);
            EditorApplication.delayCall += OnEditorUpdate;
        }
    }
}