using System;
using System.IO;
using System.Text;
using StarkSDKTool;
using UnityEditor;
using UnityEngine;
using File = Alphaleonis.Win32.Filesystem.File;

namespace TyphoonUnitySDK
{
    /// <summary>
    /// 抖音IOS发布流程
    /// </summary>
    public class PublishDouyinIOS : IPublish
    {
        public void Publish(PublishSetting setting)
        {
            var result = new PublishResult();

            if (string.IsNullOrEmpty(DouyinConfig.Default.AppId))
            {
                UniEditor.ShowMessageBox("appid不可为空,请在发布窗口中配置", null);
                return;
            }

            if (string.IsNullOrEmpty(DouyinConfig.Default.ApkName))
            {
                UniEditor.ShowMessageBox("apk文件名不可为空,请在发布窗口中配置", null);
                return;
            }

            var sb = new StringBuilder();
            if (string.IsNullOrEmpty(AppConfig.DouyinBannerId))
            {
                sb.AppendLine("缺少banner id ");
            }

            if (string.IsNullOrEmpty(AppConfig.DouyinIntersId))
            {
                sb.AppendLine("缺少插页广告 id ");
            }


            if (string.IsNullOrEmpty(AppConfig.DouyinVideoId))
            {
                sb.AppendLine("缺少视频广告 id ");
            }


            if (sb.Length > 0)
            {
                sb.AppendLine("仍然发布吗?");
                var check = EditorUtility.DisplayDialog("提示", sb.ToString(), "是", "否");
                if (!check)
                {
                    return;
                }
            }

            Debug.Log("调用抖音wasm发布逻辑");
            var zipPath =
                $".typhoonoutput/{DouyinConfig.Default.ApkName}_douyin_webgl_{DateTime.Now.ToString("yyyyMMdd_HHmmss")}.zip";
            UniEditor.CreateDirIfNotExist(Path.GetDirectoryName(zipPath));
            var isSuccess = Builder.BuildWebGL(StarkBuilderSettings.Instance, zipPath, out var cancel);
            if (cancel)
            {
                Debug.Log("取消发布");
            }

            if (isSuccess)
            {
                if (File.Exists(zipPath))
                {
                    INI.DouyinIOSFilePath = zipPath;
                }

                EditorUtility.RevealInFinder(zipPath);
            }
        }
    }
}