using System.IO;
using System.Text;
using StarkSDKTool.API;
using UnityEditor;
using UnityEngine;

namespace TyphoonUnitySDK
{
    public class PublishDouyinAndroid : 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;
                }
            }

            PublishTool.SwitchToApk();
            Debug.Log("调用抖音Native发布逻辑");
            var buildResult = BuildMananger.Build(false, false, DouyinConfig.Default.ApkName,
                DouyinConfig.Default.AppId);
            var output = buildResult.OutputPath;
            //写入导出目录
            INI.DouyinApkFilePath = output;
            Debug.Log($"导出目录：{output}");
            if (buildResult.Sucess && File.Exists(output))
            {
                //复制到指定目录
                var path = $".typhoonoutput/{Path.GetFileName(output)}";
                Debug.Log($"复制导出文件到：{path},删除旧文件：{output}");
                var dir = Path.GetDirectoryName(path);
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                    AssetDatabase.Refresh();
                }

                File.Copy(output, path, true);
                UniEditor.DeleteFile(output);
                EditorUtility.RevealInFinder(path);
                if (File.Exists(path))
                {
                    INI.DouyinApkFilePath = path;
                }

                Debug.Log("发布成功");
            }
        }
    }
}