using System;
using GFGGame.Launcher;
using UnityEngine;
using UniFramework.Event;
namespace GFGGame
{
    public class LauncherController
    {
        private static EventGroup eventGroup = new EventGroup();
        /// 
        /// 初始化启动器配置
        /// 
        public static void InitLauncherCfg()
        {
            LauncherView.Instance.SetDesc("正在检查更新...");
            var url = LauncherConfig.cfgUrl.Replace("{cfgName}", LauncherConfig.cfgName);
            url = url + "?t=" + DateTime.Now.Ticks;
            HttpTool.Instance.Get(url, (string json) =>
            {
                LauncherConfig.InitPlatform(json);
                CheckShowAgreeView(CheckGameStatus);
            });
        }
        private static void CheckShowAgreeView(Action onSuccess)
        {
            if (LocalCache.GetBool(LauncherConfig.LAST_LOGIN_IS_AGREE_KEY, false))
            {
                onSuccess?.Invoke();
            }
            else
            {
                LauncherAgreeView.Instance.Open(() => {
                    onSuccess?.Invoke();
                });
            }
        }
        public static void CheckGameStatus()
        {
            if (LauncherConfig.serverStatus == 1)
            {
                if(string.IsNullOrEmpty(LauncherConfig.statusPrompt))
                {
                    LauncherConfig.statusPrompt = "游戏正在维护中,请稍后再试。";
                }
                Alert.Show(LauncherConfig.statusPrompt)
                    .SetLeftButton(true, "知道了", (data) =>
                    {
                        Application.Quit();
                    });
            }
            else
            {
                InitSDK();
            }
        }
        private static void InitSDK()
        {
            InitReporter();
            InitBugly();
            eventGroup.AddListener(OnInitPlatform);
            QDManagerInit.InitPlatform();
        }
        private static void OnInitPlatform(IEventMessage obj)
        {
            LauncherEvent.InitPlatformResult initPlatformResult = obj as LauncherEvent.InitPlatformResult;
            if (initPlatformResult != null)
            {
                if(initPlatformResult.success)
                {
                    OnInitSDKSuccess();
                }
                else
                {
                    OnInitSDKFail();
                }
            }
        }
        private static void OnInitSDKFail()
        {
            Alert.Show("初始化平台sdk失败!")
                .SetRightButton(true, "重试", (t) => { QDManagerInit.InitPlatform(); });
        }
        private static void OnInitSDKSuccess()
        {
#if UNITY_EDITOR
            InitResVersion();
#else
            CheckApkVersion();
#endif
        }
        private static void CheckApkVersion()
        {
            var versionTarget = LauncherConfig.apkVersion;
            var version = Application.version;
            if (VersionUtil.compare(version, versionTarget))
            {
                QDManagerInit.UpdateApp();
            }
            else
            {
                InitResVersion();
            }
        }
        private static void InitResVersion()
        {
            VersionController.Instance.Init();
        }
        public static void OnVersionCompleted()
        {
            StartGame();
        }
        private static void StartGame()
        {
            LauncherView.Instance.SetDesc($"正在初始化...");
            HotUpdateCodeLoader.Instance.StartLoad();
        }
        private static void InitReporter()
        {
            Reporter reporter = GameObject.Find("Reporter").GetComponent();
            reporter.numOfCircleToShow = 10;
            reporter.isOpen = LauncherConfig.onDebug > 0;
        }
        private static void InitBugly()
        {
            BuglyAgent.ConfigDebugMode(true);
            // 注册日志回调,替换使用 'Application.RegisterLogCallback(Application.LogCallback)'注册日志回调的方式
            // BuglyAgent.RegisterLogCallback (CallbackDelegate.Instance.OnApplicationLogCallbackHandler);
#if UNITY_IPHONE || UNITY_IOS
        BuglyAgent.InitWithAppId ("f8cf2b57f3");
#elif UNITY_ANDROID
            if (LauncherConfig.netType == LauncherConfig.EnumNetType.LOCAL)
            {
                BuglyAgent.InitWithAppId("766c5bdb0f");
            }
            else if (LauncherConfig.netType == LauncherConfig.EnumNetType.PUBLIC)
            {
                BuglyAgent.InitWithAppId("b6d0b1b8c5");
            }
#endif
            // 如果你确认已在对应的iOS工程或Android工程中初始化SDK,那么在脚本中只需启动C#异常捕获上报功能即可
            BuglyAgent.EnableExceptionHandler();
        }
    }
}