using System;
using System.Collections.Generic;
using AppsFlyerSDK;
using asap.core;
using ThinkingData.Analytics;
using tysdk;
using UnityEngine;
using UnityEngine.UI;

public class SDKTest : MonoBehaviour
{
    [SerializeField]
    private Button _InitBtn;
    [SerializeField]
    private Button _loginGuestBtn;
    [SerializeField]
    private Button _loginGoogleBtn;
    [SerializeField]
    private Button _loginFbBtn;
    [SerializeField]
    private Button _loginAppleBtn;
    [SerializeField]
    private Button _loginTokenBtn;
    [SerializeField]
    private Button _linkGoogleBtn;
    [SerializeField]
    private Button _checkGoogleBtn;
    [SerializeField]
    private Button _linkFacbookBtn;
    [SerializeField]
    private Button _linkAppleBtn;
    [SerializeField]
    private Button _checkFacbookBtn;
    [SerializeField]
    private Button _logOutBtn;
    [SerializeField]
    private Button _payTestBtn;
    [SerializeField]
    private Button _payListBtn;
    [SerializeField]
    private Button _gaTestBtn;
    [SerializeField]
    private Button _gaAppMaxBtn;
    [SerializeField]
    private Button _ATTBtn;
    [SerializeField]
    private Button _signoutBtn;
    [SerializeField]
    private Text _messageTxt;

    void Start()
    {
        Debug.Log("SDKTest Start");
        //===============================================================================
        //======================      Test Server             ===========================
        UnityBridgeFunc.UnityResetServerUrl("https://128-hwsfsdk-sdk-test01.qijihdhk.com");
        IObjectSerializer serializer = new ObjectSerializer();
        IConfig config = new Config(serializer);
        GContext.container.RegisterInstance<IConfig>(config);
        config.Set("AGG_SERVER", "https://128-hwsfsdk-sdk-test01.qijihdhk.com");
        //======================      Test Server             ===========================
        //===============================================================================
        //
        _InitBtn.onClick.AddListener(Init);
        _loginGuestBtn.onClick.AddListener(() => OnLogin(EAccoutType.hwGuest));
        _loginGoogleBtn.onClick.AddListener(() => OnLogin(EAccoutType.hwGoogle));
        _loginFbBtn.onClick.AddListener(() => OnLogin(EAccoutType.hwFacebook));
#if UNITY_IOS
        _loginAppleBtn.onClick.AddListener(() => OnLogin(EAccoutType.Apple));
#endif
        _loginTokenBtn.onClick.AddListener(OnLoginByToken);
        _logOutBtn.onClick.AddListener(OnLogout);
        _linkGoogleBtn.onClick.AddListener(OnLinkGoogle);
        _checkGoogleBtn.onClick.AddListener(OncheckGoogle);
        _linkFacbookBtn.onClick.AddListener(OnLinkFacebook);    
        _checkFacbookBtn.onClick.AddListener(OncheckFacebook);
        _payTestBtn.onClick.AddListener(OnPayTestBtn);
        _payListBtn.onClick.AddListener(OnPayListBtn);
        _gaTestBtn.onClick.AddListener(OnGaBtn);
        _gaAppMaxBtn.onClick.AddListener(OnAppMaxBtn);
        _ATTBtn.onClick.AddListener(OnATTBtn);
        _signoutBtn.onClick.AddListener(OnSignoutBtn);
        Debug.Log("SDKTest Started");
    }

    void Init()
    {
        TYSdkFacade.Instance.Init();
        TDAnalytics.Init("0caf287574bd4a9bb08be8995705ef6f", "https://122-slg-online01.qijihdhk.com:8991");

        AppsFlyer.setIsDebug(true);
#if UNITY_IOS
        AppsFlyer.initSDK("rSySeWtvKabfbPZE7Lmx7C", "6505145935");
#elif UNITY_ANDROID
        AppsFlyer.initSDK("rSySeWtvKabfbPZE7Lmx7C", null);
#endif
        AppsFlyer.startSDK();
        AppsFlyerAdRevenue.start();

        InitializeRewardedAds();
    }

    int retryAttempt;

    public void InitializeRewardedAds()
    {
        // Attach callback
        MaxSdkCallbacks.Rewarded.OnAdLoadedEvent += OnRewardedAdLoadedEvent;
        MaxSdkCallbacks.Rewarded.OnAdLoadFailedEvent += OnRewardedAdLoadFailedEvent;
        MaxSdkCallbacks.Rewarded.OnAdDisplayedEvent += OnRewardedAdDisplayedEvent;
        MaxSdkCallbacks.Rewarded.OnAdClickedEvent += OnRewardedAdClickedEvent;
        MaxSdkCallbacks.Rewarded.OnAdRevenuePaidEvent += OnRewardedAdRevenuePaidEvent;
        MaxSdkCallbacks.Rewarded.OnAdHiddenEvent += OnRewardedAdHiddenEvent;
        MaxSdkCallbacks.Rewarded.OnAdDisplayFailedEvent += OnRewardedAdFailedToDisplayEvent;
        MaxSdkCallbacks.Rewarded.OnAdReceivedRewardEvent += OnRewardedAdReceivedRewardEvent;

        MaxSdkCallbacks.OnSdkInitializedEvent += (MaxSdkBase.SdkConfiguration sdkConfiguration) =>
        {
            Debug.Log($"[MaxSdk::OnSdkInitializedEvent] Init:{sdkConfiguration.IsSuccessfullyInitialized}");
        };
        MaxSdk.InitializeSdk();
    }

    private async void OnLogin(EAccoutType accoutType)
    {
        _messageTxt.text = string.Empty;
        Debug.LogError($"[AggSdk::OnLogin] accoutType : {accoutType}");
        var info = await TYSdkFacade.Instance.Login(accoutType);
        _messageTxt.text = $"Login:  {info.isSuccess}";
        if (info.isSuccess)
        {
            _messageTxt.text += $"\n{info.msg}";
            _messageTxt.text += $"\n{TYSdkFacade.TYAccountInfo.token}";
        }
    }

    private async void OnLoginByToken()
    {
        _messageTxt.text = string.Empty;
        Debug.LogError("[AggSdk::OnLoginByToken]");
        var info = await TYSdkFacade.Instance.LoginByToken();
        _messageTxt.text = $"Login:  {info.isSuccess}";
        if (info.isSuccess)
        {
            _messageTxt.text += $"\n{info.msg}";
            _messageTxt.text += $"\n{TYSdkFacade.TYAccountInfo.token}";
        }
    }

    private void OnLogout()
    {
        TYSdkFacade.Instance.Logout();
    }

    public async void OnPayTestBtn()
    {
        _messageTxt.text = "";
        if (sku == null){
            _messageTxt.text = "no product";
            return;
        } 
        PaymentInfo payResult = await TYSdkFacade.Instance.Pay(sku, 1);
        _messageTxt.text = "\n" + $"Success : {payResult.isSuccess}";
        _messageTxt.text += "\n" + $"message : {payResult.msg}";
    }

    SKUDetail sku = null;
    public async void OnPayListBtn()
    {
        Debug.Log("[AggSdk::PayList]");
        _messageTxt.text = "";

        ProductListInfo result = await TYSdkFacade.Instance.GetSKUList();
        if (result.code == 0)
        {
            _messageTxt.text = "products count:::" + result.products.Count;
            _messageTxt.text += "\n" + result.products[0].ToString();
            sku = result.products[0];
        }
        else
        {
            _messageTxt.text = "get products fail ,code:" + result.code;
        }

    }

    public void OnGaBtn()
    {
        //Debug.LogError("Ga ask");
        //using (var e = GAEvent.TackEvent("idcheckdone"))
        //{
            //e.AddContent("test ga", true);
        //}
    }

 /* 
   Android AD ID
c6c49a100de8496c
05c86d0f2be7b55b
7cf556b464448b7b
b6c56eb121b10c98

   iOS AD ID
24414b2f75660ea4
86409c4730a1d9bb
ec3c8fd688cdb5e2
eb68f93a08156e04
*/


    const string AD_ID = "24414b2f75660ea4";

    public void OnAppMaxBtn()
    {
        if (MaxSdk.IsRewardedAdReady(AD_ID))
        {
            MaxSdk.ShowRewardedAd(AD_ID);
        }
        else
        {
            _messageTxt.text = "AD Not Ready, Load now";
            LoadAd();
        }
    }

    public void OnATTBtn()
    {
        UnityBridgeFunc.RequestATT();
    }

    private void LoadAd()
    {
        Debug.Log($"[AD LOG] LoadAd {AD_ID}");
        MaxSdk.LoadRewardedAd(AD_ID);
    }

    private void OnRewardedAdLoadedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        string msg = $"[AD LOG]Rewarded ad loaded. ID: {adInfo.AdUnitIdentifier}";
        _messageTxt.text = msg;
        Debug.Log(msg);
        retryAttempt = 0;
    }

    private void OnRewardedAdLoadFailedEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo)
    {
        // Rewarded ad failed to load
        // AppLovin recommends that you retry with exponentially higher delays, up to a maximum delay (in this case 64 seconds).

        retryAttempt++;
        double retryDelay = Math.Pow(2, Math.Min(6, retryAttempt));
        string msg = $"[AD LOG]Rewarded ad failed to load. ID: {adUnitId}. Reason: {errorInfo.Message}. Attempt: {retryAttempt}. Delay: {retryDelay}s.";
        _messageTxt.text =  msg;
        Debug.Log(msg);

        Invoke("LoadAd", (float)retryDelay);
    }

    private void OnRewardedAdDisplayedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) { }

    private void OnRewardedAdFailedToDisplayEvent(string adUnitId, MaxSdkBase.ErrorInfo errorInfo, MaxSdkBase.AdInfo adInfo)
    {
        // Rewarded ad failed to display. AppLovin recommends that you load the next ad.
        string msg = $"[AD LOG]Rewarded ad failed to display. ID: {adUnitId}. Reason: {errorInfo.Message}";
        _messageTxt.text = msg;
        Debug.Log(msg);
        LoadAd();
    }

    private void OnRewardedAdClickedEvent(string adUnitId, MaxSdkBase.AdInfo adInfo) { }

    private void OnRewardedAdHiddenEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        // Rewarded ad is hidden. Pre-load the next ad
        string msg = $"[AD LOG]Rewarded ad hidden. ID: {adUnitId}.";
        _messageTxt.text = msg;
        Debug.Log(msg);
        LoadAd();
    }

    private void OnRewardedAdReceivedRewardEvent(string adUnitId, MaxSdk.Reward reward, MaxSdkBase.AdInfo adInfo)
    {
        string msg = $"[AD LOG]Rewarded ad received reward. ID: {adUnitId}. Type: {reward}. Amount: {reward.Amount}";
        _messageTxt.text = msg; 
        Debug.Log($"[AD LOG]Rewarded ad received reward \n {reward.ToString()} \n {adInfo.ToString()}");
    }

    private void OnRewardedAdRevenuePaidEvent(string adUnitId, MaxSdkBase.AdInfo adInfo)
    {
        string msg = $"[AD LOG]Rewarded ad revenue paid. ID: {adUnitId}.";
        _messageTxt.text = msg;
        Debug.Log($"[AD LOG]Rewarded ad revenue paid \n {adInfo.ToString()}");
    }


    private async void OnLinkGoogle()
    {
        _messageTxt.text = string.Empty;
        var isSuccess = await TYSdkFacade.Instance.LinkAccount(EAccoutType.hwGoogle);
        _messageTxt.text = $"\n link google account : {isSuccess}";
    }

    private async void OnLinkFacebook()
    {
        _messageTxt.text = string.Empty;
        var isSuccess = await TYSdkFacade.Instance.LinkAccount(EAccoutType.hwFacebook);
        _messageTxt.text = $"\n link facebook account : {isSuccess}";
    }

    private async void OncheckGoogle()
    {
        _messageTxt.text = string.Empty;
        var isSuccess = await TYSdkFacade.Instance.LinkCheck(EAccoutType.hwGoogle);
        _messageTxt.text = $"\n google account linked : {isSuccess}";
    }

    private async void OncheckFacebook()
    {
        _messageTxt.text = string.Empty;
        var isSuccess = await TYSdkFacade.Instance.LinkCheck(EAccoutType.hwFacebook);
        _messageTxt.text = $"\n facebook account linked : {isSuccess}";
    }

    private void OnSignoutBtn()
    {
        TYSdkFacade.Instance.Signout();
    }

    /*
    public void OnTaBtn()
    {
        // 初始化SDK
        TDAnalytics.Init("0caf287574bd4a9bb08be8995705ef6f", "https://122-slg-online01.qijihdhk.com:8991");
        // //如果用户已登录，可以设置用户的账号ID作为身份唯一标识
        // TDAnalytics.Login("TA");
        //设置公共事件属性以后，每个事件都会带有公共事件属性
        // Dictionary<string, object> superProperties = new Dictionary<string, object>();
        // superProperties["channel"] = "ta";//字符串
        // superProperties["age"] = 1;//数字
        // superProperties["isSuccess"] = true;//布尔
        // superProperties["birthday"] = DateTime.Now;//时间
        // superProperties["object"] = new Dictionary<string, object>(){{ "key", "value"}};//对象
        // superProperties["object_arr"] = new List<object>() {new Dictionary<string, object>(){{ "key", "value" }}};//对象组
        // superProperties["arr"] = new List<object>() { "value" };//数组
        // TDAnalytics.SetSuperProperties(superProperties);//设置公共事件属性
        //开启自动采集事件
        // TDAnalytics.EnableAutoTrack(TDAutoTrackEventType.AppInstall | TDAutoTrackEventType.AppStart | TDAutoTrackEventType.AppEnd);
        //发送事件
        // Dictionary<string, object> properties = new Dictionary<string, object>(){{"product_name", "商品名")}};
        // TDAnalytics.Track("product_buy", properties);
        //设置用户属性
        // TDAnalytics.UserSet(new Dictionary<string, object>(){{"user_name", "TA"}});

    }
    */


}
