using System;
using System.IO;
using UnityEditor;
using UnityEditor.Build.Reporting;
using UnityEngine;
using YG;
using YG.Insides;

namespace TyphoonUnitySDK
{
    public class PublishYandexGames : IPublish
    {
        public static void ApplyYandexGamesSettings()
        {
            var config = YandexGamesConfig.Default;

            //修改模板横竖屏
            var html = "Assets/WebGLTemplates/YandexGames/index.html";
            switch (config.Orientation)
            {
                case YandexGamesConfig.ScreenOrientation.Portrait:
                {
                    var template =
                        $"{UniEditor.PathRoot}/Editor/Templates/yandex_games_html_portrait_template.txt";
                    File.Copy(template, html, true);
                }
                    break;
                case YandexGamesConfig.ScreenOrientation.Landscape:
                {
                    var template =
                        $"{UniEditor.PathRoot}/Editor/Templates/yandex_games_html_landscape_template.txt";
                    File.Copy(template, html, true);
                }
                    break;
            }

            var platformFile = "Assets/PluginYourGames/Platforms/YandexGames/YandexGames.asset";
            var platformSettings = AssetDatabase.LoadAssetAtPath<PlatformSettings>(platformFile);
            platformSettings.projectSettings.autoPauseGame = false;
            EditorUtility.SetDirty(platformSettings);
            var infoYG2File = "Assets/PluginYourGames/Resources/SettingsYG2.asset";
            var infoYg = AssetDatabase.LoadAssetAtPath<InfoYG>(infoYG2File);
            infoYg.InterstitialAdv.interAdvInterval = config.IntersInterval;
            infoYg.RewardedAdv.skipInterAdvAfterReward = config.SkipIntersAfterShowRewardFlag;
            infoYg.Basic.autoPauseGame = false;
            infoYg.Basic.editEventSystem = false;
            CopyBackground();
            EditorUtility.SetDirty(infoYg);
            AssetDatabase.SaveAssets();
        }

        public void Publish(PublishSetting setting)
        {
            //设置打包参数
            var infoYG2File = "Assets/PluginYourGames/Resources/SettingsYG2.asset";
            var infoYg = AssetDatabase.LoadAssetAtPath<InfoYG>(infoYG2File);
            if (infoYg == null)
            {
                UniEditor.ShowMessageBox($"找不到：{infoYG2File}", null);
                return;
            }

            if (YandexGamesConfig.Default.IntersInterval < 0)
            {
                UniEditor.ShowMessageBox($"[参数错误] 插页广告展示最小间隔(秒),需要大于等于0,去设置？", () => { PublishWindow.Open(setting); });
                return;
            }

            ApplyYandexGamesSettings();
            infoYg.Basic.autoPauseGame = false;
            infoYg.Basic.editEventSystem = false;
            EditorUtility.SetDirty(infoYg);
            AssetDatabase.SaveAssets();
            var config = YandexGamesConfig.Default;
            PublishResult result = new PublishResult();
            //导出到指定目录
            var path =
                $".typhoonoutput/{PlayerSettings.companyName}_{PlayerSettings.productName}_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            if (!string.IsNullOrEmpty(config.ExportPath))
            {
                path =
                    $".typhoonoutput/{config.ExportPath}_{DateTime.Now.ToString("yyyyMMddHHmmss")}";
            }

            result.YandexGamesProj = 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)
            {
                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 static void CopyBackground()
        {
            var config = YandexGamesConfig.Default;
            var infoYG2File = "Assets/PluginYourGames/Resources/SettingsYG2.asset";
            var infoYg = AssetDatabase.LoadAssetAtPath<InfoYG>(infoYG2File);
            var imagesFolder = "Assets/WebGLTemplates/YandexGames/Images";
            UniEditor.CreateDirIfNotExist(imagesFolder);
            AssetDatabase.Refresh();
            if (config.Background == null)
            {
                infoYg.Templates.backgroundImgFormat = InfoYG.TemplatesSettings.BackgroundImageFormat.Gradient;
                var block32 = $"{UniEditor.PathRoot}/Editor/Texture/black_32x32.png";
                var backgroundPath = "Assets/WebGLTemplates/YandexGames/Images/background.png";
                File.Copy(block32, backgroundPath, true);
                AssetDatabase.Refresh();
            }
            else
            {
                var bgPath = AssetDatabase.GetAssetPath(config.Background);
                if (bgPath.EndsWith(".png"))
                {
                    infoYg.Templates.backgroundImgFormat = InfoYG.TemplatesSettings.BackgroundImageFormat.PNG;
                    var backgroundPath = "Assets/WebGLTemplates/YandexGames/Images/background.png";
                    File.Copy(bgPath, backgroundPath, true);
                    AssetDatabase.Refresh();
                }
                else if (bgPath.EndsWith(".jpg"))
                {
                    infoYg.Templates.backgroundImgFormat = InfoYG.TemplatesSettings.BackgroundImageFormat.JPG;
                    var backgroundPath = "Assets/WebGLTemplates/YandexGames/Images/background.jpg";
                    File.Copy(bgPath, backgroundPath, true);
                    AssetDatabase.Refresh();
                }
                else
                {
                    infoYg.Templates.backgroundImgFormat = InfoYG.TemplatesSettings.BackgroundImageFormat.Gradient;
                }
            }

            EditorUtility.SetDirty(infoYg);
            AssetDatabase.SaveAssets();
        }
    }
}