using UnityEngine;
using System.Collections.Generic;
using Combo.Core;
using Combo.Platform;
using Sentry;

namespace Combo
{
    // https://docs.unity3d.com/ScriptReference/RuntimeInitializeOnLoadMethodAttribute.html
    internal class Initializer
    {
        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.AfterAssembliesLoaded)]
        public static void SetupByAfterAssembliesLoaded()
        {
            Debug.Log("[ComboSDK] SetupByAfterAssembliesLoaded");
            SentryManager.Setup();
        }

        [RuntimeInitializeOnLoadMethod(RuntimeInitializeLoadType.BeforeSceneLoad)]
        public static void SetupByBeforeSceneLoad()
        {
            Debug.Log("[ComboSDK] SetupByBeforeSceneLoad");
            // 数数有自己的 Prefab, 只能放到场景初始化阶段
            ThinkingDataManager.Setup();

            var setupOptions = new SetupOptions()
            {
                gameId = Configuration.Instance.GameId,
                publishableKey = Configuration.Instance.PublishableKey,
                endpoint = Configuration.Instance.Endpoint,
            };
            
            // 添加 Combo SDK for Unity 版本号 与 Unity 版本号
            PutExtraWithVersions(setupOptions.extra);
            
            ThinkingDataManager.PutExtraWithDistinctId(setupOptions.extra);
            Native.Setup(setupOptions, HandleSetup);

            if (Configuration.Instance.EnableKeepRenderingOnPause)
            {
                Native.KeepRenderingOnPause();
            }
        }

        private static void HandleSetup(Result<SetupResult> result)
        {
            if (result.IsSuccess)
            {
                Debug.Log("[ComboSDK] finished to setup");
                if (result.Data != null && result.Data.thinkingDataSuperProperties != null)
                {
                    Debug.Log("[ComboSDK] SetSuperProperties");
                    ThinkingDataManager.SetSuperProperties(result.Data.thinkingDataSuperProperties);
                }
            }
            else
            {
                var title = "[ComboSDK] Setup Error";
                var info = $"Error Code: {result.Error.Code}\nError Message: {result.Error.Message}\nError DetailMessage: {result.Error.DetailMessage}";
                SentrySdk.CaptureMessage($"{title}\n{info}", (scope)=>
                {
                    scope.SetTag("combo.sdk.error", title);
                    scope.Fingerprint = new List<string>() {title};
                });
            }
        }

        private static void PutExtraWithVersions(Dictionary<string, object> extra)
        {
            extra["unity_version"] =  Application.unityVersion;
            extra["combo_sdk_unity_version"] =  Version.SDKVersion;
        }
    }
}
