using System;
using System.Collections;
using UnityEngine;
using System.Collections.Generic;
using Touka.GameLogic;

public partial class ToukaAdManager : ToukaSingletonMonoBehaviour<ToukaAdManager>
{
    /// <summary>
    /// 标明当前界面是否可以显示banner
    ///
    /// banner load成功，如果当前可显示banner，就会直接显示出来
    /// </summary>
    public static bool isCurrCanShowBanner = true;

    #region Consts
    private const int RETRY_TIMES_COUNT = 3;       // 广告重试次数
    #endregion

    private int m_bannerRetryTimes = RETRY_TIMES_COUNT;     // bnner重试次数
    private int m_intersRetryTimes = RETRY_TIMES_COUNT;     // 插屏重试次数
    private int m_videoRetryTimes = RETRY_TIMES_COUNT;    // 激励视频重试次数
    private int m_nativeRetryTimes = RETRY_TIMES_COUNT;         // native重试次数

    private bool m_noAds = false;       // 是否有广告 true:没广告（除激励视频外） false:有广告 - 用于购买去广告后
    private bool m_initialized = false;

    public float NativeWidth = 0f;      // native 宽
    public float NativeHeight = 0f;     // native 高

    private IToukaAdInterface toukaAds;

    /// <summary>
    /// init
    /// </summary>
	public void Init () {

        if (StaticOtherConfig.IsDebugLog)
        {
            Debug.unityLogger.logEnabled = true;
        }
        else
        {
            Debug.unityLogger.logEnabled = false;
        }

        if (m_initialized) return;
        m_initialized = true;

#if UNITY_EDITOR
        return;
#endif

        m_noAds = ToukaUtils.GetPlayerPrefsIntByKey(StaticStringsPlayerPrefs.HasRemoveAds) != 0;

        NativeWidth = float.Parse(ToukaUtils.GetPlayerPrefsStringByKey(StaticStringsPlayerPrefs.NativeWidthSaved, "0"));
        NativeHeight = float.Parse(ToukaUtils.GetPlayerPrefsStringByKey(StaticStringsPlayerPrefs.NativeHeightSaved, "0"));

        toukaAds = ToukaSDKAdapter.Instance;

        // 初始化广告id，设置listener
        toukaAds.Init();

        Debug.Log("[ToukaAdManager] before loadads.");
        StartCoroutine(LoadAds());
    }

    /// <summary>
    /// load ads
    /// </summary>
    /// <returns></returns>
    IEnumerator LoadAds()
    {
        Debug.Log("[ToukaAdManager] IEnumerator LoadAds.");

        if (StaticStringsKey.BannerSwitch)
        {
            Debug.Log("[ToukaAdManager] 初始化banner");
            LoadBanner();

            yield return new WaitForSeconds(2);
        }

        if (StaticStringsKey.RewardSwitch)
        {
            Debug.Log("[ToukaAdManager] 初始化激励视频");
            LoadVideo();

            yield return new WaitForSeconds(2);
        }

        if (StaticStringsKey.InterSwitch)
        {
            Debug.Log("[ToukaAdManager] 初始化插屏");
            LoadInterstitial();

            yield return new WaitForSeconds(2);
        }

        if (StaticStringsKey.NativeSwitch)
        {
            Debug.Log("[ToukaAdManager] 初始化native");
            LoadNative();
        }
    }

    /// <summary>
    /// refresh remove ads
    /// </summary>
    public void RefreshVIPStatus()
    {
        m_noAds = ToukaUtils.GetPlayerPrefsIntByKey(StaticStringsPlayerPrefs.HasRemoveAds) != 0;
        if (m_noAds)
        {
            HideBanner(true);
        }

        Debug.Log("[ToukaAdManager] 购买去广告成功，告诉SDK不再显示开屏！！");
    }

    #region banner

    /// <summary>
    /// show banner
    /// </summary>
    public void ShowBanner()
    {
#if UNITY_EDITOR
        return;
#endif
        if (!StaticStringsKey.BannerSwitch)
        {
            return;
        }

        Debug.Log("in ToukaAdManager, ShowBanner.");
		if (m_noAds) {
			Debug.Log ("Touka: VIP don't show banner");
            toukaAds.RemoveBanner (true);
			return;
		}

        if (!isCurrCanShowBanner)
        {
            Debug.Log("Touka: this view cannot show banner");
            return;
        }

        Debug.Log ("Touka: Show banner real ");
        toukaAds.ShowBanner ();
    }

    /// <summary>
    /// force reload banner
    /// </summary>
    public void ForceReloadBanner()
    {
        Debug.Log("Touka: ForceReloadBanner");
        if (!StaticStringsKey.BannerSwitch)
        {
            return;
        }

		LoadBanner();
    }

    /// <summary>
    /// Hides the banner.
    /// </summary>
    /// <param name="_clean">true:remove  false:hide</param>
    public void HideBanner(bool _clean)
    {
#if UNITY_EDITOR
        return;
#endif
        Debug.Log("in ToukaAdManager, HideBanner, _clean:" + _clean);

        if (!StaticStringsKey.BannerSwitch)
        {
            return;
        }
        toukaAds.RemoveBanner(_clean);
    }

    /// <summary>
    /// isReady Banner
    /// </summary>
    public bool IsReadyBanner
    {
        get
        {
#if UNITY_EDITOR
            return true;
#endif
            return toukaAds.IsReadyBanner();
        }
    }


    #endregion

    #region 插屏 Interstitial
    /// <summary>
    /// show iv
    /// </summary>
    /// <param name="callback"></param>
    /// <param name="_interId"></param>
    /// <param name="_extraParam"></param>
    public void ShowInterstitial (Action<ToukaIntersitialStatus> callback, string _extraParam = "") {

#if UNITY_EDITOR
        Debug.Log("[ToukaAdManager] Show Interstitial call");
        if (callback != null) callback(ToukaIntersitialStatus.FAIL);
        return;
#endif

        if (m_noAds)
        {
            Debug.Log("[ToukaAdManager] VIP don't show interstitial");
            if (callback != null) callback(ToukaIntersitialStatus.FAIL);
            return;
        }

        Debug.Log("[ToukaAdManager] Show Interstitial ");

		if (toukaAds.IsReadyIntersitial ()) {
            ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_isready_iv_success);
            toukaAds.ShowIntersitial((status) => {
                if (status == ToukaIntersitialStatus.CLOSE || status == ToukaIntersitialStatus.FAIL)
                {
                    AudioAdaper.Reset();
                    if (callback != null) callback(status);     // 回调改到这里了
                    AudioAdaper.SetGameSound();     // 恢复原游戏声音状态
                    LoadInterstitial();
                    if (status == ToukaIntersitialStatus.FAIL)      // 如果是失败回调，就做失败打点
                    {
                        ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_iv_ad_show_failed, new System.Collections.Generic.Dictionary<string, string>() { { StaticStringsEvent.Event_Type_TKInner_ad_position, _extraParam } });
                    }
                }
                else if (status == ToukaIntersitialStatus.SHOW)
                {
                    AudioAdaper.Pause();
                    Debug.Log("[ToukaAdManager] UMENG 插屏SHOW上报");
                    ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_iv_ad_show, new System.Collections.Generic.Dictionary<string, string>() { { StaticStringsEvent.Event_Type_TKInner_ad_position, _extraParam } });
                    ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_ivrv_ad_show);

                    CheckIn24UploadToConversionValue();
                    IncreateVideoAndIntersitialShowCount(false);
                }
            });
        }
        else
        {
            if (callback != null) callback(ToukaIntersitialStatus.FAIL);
            ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_isready_iv_failure);
            LoadInterstitial();
        }
    }

    /// <summary>
    /// isReady iv
    /// </summary>
    /// <param name="_interId"></param>
    /// <returns></returns>
    public bool IsReadyIntersitial()
    {
#if UNITY_EDITOR
        return false;
#endif
        bool isReadyInter = toukaAds.IsReadyIntersitial();
        Debug.Log("[ToukaAdManager] isReadyInter : " + isReadyInter);
        return isReadyInter;
    }

    #endregion

    #region 激励视频 RewardVideo

    /// <summary>
    /// show video
    /// </summary>
    /// <param name="_callback"></param>
    /// <param name="_videoPlace"></param>
    /// <returns></returns>
    public bool ShowVideo(Action<ToukaVideoStatus> _callback, ToukaVideoPlace _videoPlace)
    {

        ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_ad_button_click, new System.Collections.Generic.Dictionary<string, string>() { { StaticStringsEvent.Event_Type_TKInner_ad_position, _videoPlace.ClickPlace } });
#if UNITY_EDITOR
        _callback(ToukaVideoStatus.SUCCESS);
        return true;
#endif
        if (toukaAds.IsReadyVideo())
        {
            ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_isready_rv_success, new System.Collections.Generic.Dictionary<string, string>() { { StaticStringsEvent.Event_Type_TKInner_ad_position, _videoPlace.ClickPlace } });
            toukaAds.ShowVideo((status) =>
            {
                if (status == ToukaVideoStatus.CLOSE)
                {
                    AudioAdaper.SetGameSound();     // 恢复原游戏声音状态
                    LoadVideo();
                }
                if (status == ToukaVideoStatus.SHOW)
                {
                    AudioAdaper.Pause();
                    // 播激励视频上报打点
                    Debug.Log("UMENG 播激励视频上报打点");
                    ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_rv_ad_show, new System.Collections.Generic.Dictionary<string, string>() { { StaticStringsEvent.Event_Type_TKInner_ad_position, _videoPlace.ClickPlace } });
                    ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_ivrv_ad_show);
                    CheckIn24UploadToConversionValue();
                    IncreateVideoAndIntersitialShowCount(true);
                    //Time.timeScale = 0.0f;
                }
                if (status == ToukaVideoStatus.CANCEL)
                {

                }
                if (status == ToukaVideoStatus.FAIL)
                {
                    ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_rv_ad_show_fail, new System.Collections.Generic.Dictionary<string, string>() { { StaticStringsEvent.Event_Type_TKInner_ad_position, _videoPlace.ClickPlace } });
                }
                if (status == ToukaVideoStatus.SUCCESS)
                {

                }
                if (_callback != null) _callback(status);

            });
            return true;
        }
        else
        {
            if (_callback != null) _callback(ToukaVideoStatus.FAIL);

            Debug.Log("Touka: Don't show Video for hasAdReady is NO");
            //PopupTipsPanel.PopupTips(LocalizationManager.GetTermTranslation("1045"));
            ToukaAnalyticsManager.Instance.LogEventByUmeng(StaticStringsEvent.Event_Sort_TKInner_isready_rv_failure, new System.Collections.Generic.Dictionary<string, string>() { { StaticStringsEvent.Event_Type_TKInner_ad_position, _videoPlace.ClickPlace } });

            LoadVideo();
            return false;
        }
    }

    /// <summary>
    /// isReady RV
    /// </summary>
    public bool IsReadyVideo
    {
        get
        {
#if UNITY_EDITOR
            return true;
#endif
            if (toukaAds.IsReadyVideo())
            {
                Debug.Log("[ToukaAdManager] IsReadyVideo = true. ");
                return true;
            }
            else
            {
                LoadVideo();
                Debug.Log("[ToukaAdManager] IsReadyVideo = false. ");
                return false;
            }
        }
    }

    #endregion

    #region native
    /// <summary>
    /// isReady Native
    /// </summary>
    public bool IsReadyNative
    {
        get
        {
#if UNITY_EDITOR
            return false;
#endif
            return toukaAds.IsReadyNative();
        }
    }

    /// <summary>
    /// show native
    /// </summary>
    /// <param name="x"></param>
    /// <param name="y"></param>
    /// <param name="width"></param>
    /// <param name="height"></param>
    /// <returns></returns>
    public bool ShowNative(float x, float y, float width, float height)
    {
        Debug.Log("ShowNative()");
#if UNITY_EDITOR
        return false;
#endif
        Debug.Log("[ToukaAdManager] ShowNative with frame, before isReadyNative");
        if (m_noAds)
        {
            Debug.Log("Touka: VIP don't ShowNative");
            toukaAds.RemoveNative(true);
            return false;
        }
        if (IsReadyNative)
        {
            Debug.Log("Touka: ShowNative, x : " + x + " , y : " + y + " , width : " + width + " , height : " + height);
            toukaAds.ShowNative(x, y, width, height);

            return true;
        }
        else
        {
            LoadNative();
        }

        return false;
    }

    /// <summary>
    /// set native bounds first
    /// </summary>
    /// <param name="width"></param>
    /// <param name="height"></param>
    public void SetNativeBoundsFist(float width, float height)
    {
        if (ToukaUtils.FloatEqual(ToukaAdManager.Instance.NativeWidth, 0) && ToukaUtils.FloatEqual(ToukaAdManager.Instance.NativeHeight, 0))
        {
            Debug.Log("inner ---- SetNativeBoundsFist, width : " + width + " , height : " + height);
            ToukaAdManager.Instance.NativeWidth = width;
            ToukaAdManager.Instance.NativeHeight = height;

            ToukaUtils.SavePlayerPrefsStringByKeyValue(StaticStringsPlayerPrefs.NativeWidthSaved, ToukaAdManager.Instance.NativeWidth.ToString());
            ToukaUtils.SavePlayerPrefsStringByKeyValue(StaticStringsPlayerPrefs.NativeHeightSaved, ToukaAdManager.Instance.NativeHeight.ToString());

            ToukaAdManager.Instance.LoadNative();
        }
    }

    /// <summary>
    /// hide native
    /// </summary>
    /// <param name="_clean"></param>
    public void HideNative(bool _clean)
    {
#if UNITY_EDITOR
        return;
#endif
        if (toukaAds != null)
        {
            toukaAds.RemoveNative(_clean);
            if(_clean ==false ){
                LoadNative();    
            }
        }
    }

    #endregion

    #region Load & Reload

    /// <summary>
    /// load banner
    /// </summary>
    public void LoadBanner()
    {
		Debug.Log ("Touka: LoadBanner");
#if UNITY_EDITOR
		return;
#endif
        if (!StaticStringsKey.BannerSwitch)
        {
            return;
        }
        if (Application.internetReachability != NetworkReachability.NotReachable)
        {
            Debug.Log("start to load banner");
            toukaAds.LoadBanner((success) => {
                if (success)
                {
                    Debug.Log("in ToukaAdManager, loadBanner. success");
                    m_bannerRetryTimes = RETRY_TIMES_COUNT;
                    if (isCurrCanShowBanner)
                    {
                        Debug.Log("可以显示banner");
                        ShowBanner();
                    }
                }
                else
                {
                    Debug.Log("load banner fail");
                    ReLoadBanner();
                }
            });
        }
        else
        {
            Debug.Log("Touka: Don't load banner for NetworkReachability.NotReachable");
        }
    }

    /// <summary>
    /// load iv
    /// </summary>
    public void LoadInterstitial()
    {
        if (Application.internetReachability != NetworkReachability.NotReachable)
        {
            toukaAds.LoadInterstitial((success) =>
            {
                if (success)
                {
                    Debug.Log("加载插屏广告成功");
                    m_intersRetryTimes = RETRY_TIMES_COUNT;
                    CancelInvoke();
                }
                else
                {
                    Debug.Log("加载插屏广告失败，重新加载：" + m_intersRetryTimes);
#if UNITY_IOS
                    ReloadInterstitial();
#endif

                }
            });
        }
        else
        {
            Debug.Log("Touka: Don't load interstitial for NetworkReachability.NotReachable");
        }
    }

    /// <summary>
    /// load rv
    /// </summary>
    public void LoadVideo()
    {
        if (Application.internetReachability != NetworkReachability.NotReachable)
        {
            toukaAds.LoadVideo((success) =>
            {
                if (success)
                {
                    m_videoRetryTimes = RETRY_TIMES_COUNT;
                }
                else
                {
                    ReloadVideo();
                }
            });
        }
        else
        {
            Debug.Log("Touka: Don't load video for NetworkReachability.NotReachable");
        }

    }

    /// <summary>
    /// load native
    /// </summary>
    public void LoadNative()
    {
#if IOS_CN
        if (Application.internetReachability != NetworkReachability.NotReachable)
        {

            if(toukaAds != null)
            {
                toukaAds.LoadNative((success) =>
                {
                    if (success)
                    {
                        Debug.Log("native 加载成功");
                        m_nativeRetryTimes = RETRY_TIMES_COUNT;
                    }
                    else
                    {
                        Debug.Log("native 加载失败");
                        ReloadNative();
                    }
                });
            }
        }
        else
        {
            Debug.Log("Touka: Don't load native for NetworkReachability.NotReachable");
        }
#endif
    }

    /// <summary>
    /// reload banner
    /// </summary>
    private void ReLoadBanner()
    {
        if (!StaticStringsKey.BannerSwitch)
        {
            return;
        }
        Debug.Log("Touka: ReLoadBanner times :" + m_bannerRetryTimes);
        if (Application.internetReachability != NetworkReachability.NotReachable)
        {
            if (m_bannerRetryTimes > 0)
            {
                m_bannerRetryTimes--;
                Debug.Log("has times count, go on load again");
                LoadBanner();
            }
            else
            {
                Debug.Log("no times count, don't load again");
                m_bannerRetryTimes = RETRY_TIMES_COUNT;
            }
        }
        else
        {
            Debug.Log("Touka: Don't Reload banner for NetworkReachability.NotReachable");
        }
    }

    /// <summary>
    /// reload video
    /// </summary>
    private void ReloadVideo()
    {
        Debug.Log("Touka: ReLoadVideo, times : " + m_videoRetryTimes);
        if (Application.internetReachability != NetworkReachability.NotReachable)
        {
            if (m_videoRetryTimes > 0)
            {
                m_videoRetryTimes--;
                LoadVideo();
            }
            else
            {
                m_videoRetryTimes = RETRY_TIMES_COUNT;
            }
        }
        else
        {
            Debug.Log("Touka: Don't Reload video for NetworkReachability.NotReachable");
        }
    }

    /// <summary>
    /// reload iv
    /// </summary>
    private void ReloadInterstitial()
    {
        Debug.Log("Touka: ReLoadInterstitial, times:" + m_intersRetryTimes);
        if (m_intersRetryTimes > 0)
        {
            m_intersRetryTimes--;
            LoadInterstitial();
        }
        else
        {
            m_intersRetryTimes = RETRY_TIMES_COUNT;
        }
    }

    /// <summary>
    /// reload native
    /// </summary>
    private void ReloadNative()
    {
        Debug.Log("Touka: ReloadNative. times : " + m_nativeRetryTimes);
        if (m_nativeRetryTimes > 0)
        {
            m_nativeRetryTimes--;
            LoadNative();
        }
        else
        {
            m_nativeRetryTimes = RETRY_TIMES_COUNT;
        }
    }

#endregion

#region Utils below

    // Utils below ////////////////////////////////////////////////////////////////

    /// <summary>
    /// 判断 插屏+激励视频 总次数，是否达到了上报总次数
    /// </summary>
    /// <returns></returns>
    private bool IncreateVideoAndIntersitialShowCount(bool _video)
    {
        if (!ToukaUtilsInner.Instance.isFirstDayLogin)      // 非首日登录
        {
            return false;
        }

        string playerPrefsKey = StaticStringsPlayerPrefs.IntersitialShowCount;
        if (_video)
        {
            playerPrefsKey = StaticStringsPlayerPrefs.VideoShowCount;
        }

        // 记录 插屏/激励视频 展示次数
        var showCount = ToukaUtils.GetPlayerPrefsIntByKey(playerPrefsKey);
        ToukaUtils.SavePlayerPrefsIntByKeyValue(playerPrefsKey, showCount + 1);

        // 读取 插屏 + 激励视频 总次数
        var videoCount = ToukaUtils.GetPlayerPrefsIntByKey(StaticStringsPlayerPrefs.VideoShowCount); 
        var intersitialCount = ToukaUtils.GetPlayerPrefsIntByKey(StaticStringsPlayerPrefs.IntersitialShowCount); 

        Debug.Log("激励视频+插屏次数：" + (videoCount + intersitialCount) + ", rv onlineCount : " + StaticOnlineParams.NewUserRVCountOnlineParams.DefaultValue + " , iv onlineCount : " + StaticOnlineParams.NewUserAdsCountOnlineParams.DefaultValue);

        //if (videoCount >= int.Parse(StaticOnlineParams.NewUserRVCountOnlineParams.DefaultValue))
        //{
        //    if (ToukaUtils.IfFirstCheckPlayerPrefs(StaticStringsPlayerPrefs.TKInner_HasTenjinUploadRVCount))
        //    {
        //        Debug.Log(string.Format("看激励视频达到{0}次，上报tenjin. ", videoCount));
        //        //ToukaAnalyticsManager.Instance.LogEvent(ToukaLogType.Tenjin, StaticStringsEvent.Event_Tenjin_NewUserRVCount);     // 暂时没要求上报了  // 上报新用户观看激励视频次数
        //    }
        //}

        if ((videoCount + intersitialCount) >= int.Parse(StaticOnlineParams.NewUserAdsCountOnlineParams.DefaultValue))
        {
            if (ToukaUtils.IfFirstCheckPlayerPrefs(StaticStringsPlayerPrefs.TKInner_HasTenjinUploadADSCount))
            {
                Debug.Log(string.Format("看视频广告达到{0}次，上报tenjin. ", videoCount + intersitialCount));
                ToukaAnalyticsManager.Instance.LogEvent(ToukaLogType.Tenjin, StaticStringsEvent.Event_Tenjin_TKInner_NewUserAdsCount);
            }
        }

        return videoCount + intersitialCount >= int.Parse(StaticOnlineParams.NewUserAdsCountOnlineParams.DefaultValue);
    }

    /// <summary>
    /// iOS 14要求，24h 内新安装用户 有观看 插屏/激励视频， 则上报。
    /// </summary>
    private void CheckIn24UploadToConversionValue()
    {
        Debug.Log("CheckIn24UploadToConversionValue");

        if(ToukaUtils.GetPlayerPrefsIntByKey("Has24UploadToConversionValue") == 1)
        {
            return;
        }

        if (ToukaUtils.isNewUser())
        {
            Debug.Log("UpdateConversionValue 000011");
#if !NO_SDK
            TGiOSAdManager.Instance.UpdateConversionValue("000011");
#endif
            ToukaUtils.SavePlayerPrefsIntByKeyValue("Has24UploadToConversionValue", 1);
        }
    }

#endregion
}