package com.rgt.superr.business.ads.admob

import android.app.Activity
import android.content.Context
import com.rgt.superr.GlobalConfig
import com.rgt.superr.MyApplication
import com.rgt.superr.bean.config.AdConfigBean
import com.rgt.superr.business.ads.AdCountDownDialog.createUICountdownTimer
import com.rgt.superr.business.ads.AdCountDownDialog.showAdCountDownDialog
import com.rgt.superr.business.ads.AdEvent
import com.rgt.superr.business.ads.AdState
import com.rgt.superr.business.ads.AdsShowCallBack
import com.rgt.superr.business.ads.AdsType
import com.rgt.superr.business.ads.LimitUtils
import com.rgt.superr.utils.LogEx
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback


/**
 *插屏广告加载显示管理类
 */
class AdInterMgr {

    private val TAG = "AdInterMgr"
    private var adState = AdState<InterstitialAd>()
    private var showCallBack: AdsShowCallBack? = null

    //正在加载回调
    private var loadingCallBack: (() -> Unit)? = null

    fun show(
        activity: Activity,
        adEvent: AdEvent,
        showCallBack: AdsShowCallBack? = null
    ) {

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }

        val nowAdEvent = adEvent
        //currentAdEvent!=null 表示有缓存广告,关联reqId
        adState.currentAdEvent?.let { nowAdEvent.reqId = it.reqId }

        if (!nowAdEvent.isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.INSERT, nowAdEvent)) {
                showCallBack?.failed(2)
                return
            }
            if (LimitUtils.isIntervalLimited(nowAdEvent)) {
                showCallBack?.failed(3)
                return
            }
        }


        val needLoad = !adState.adAvailable()
//        adState.activityRef = WeakReference(activity)
        this.showCallBack = showCallBack

        if (adState.adDialog == null) {
            adState.adDialog = activity.showAdCountDownDialog()
        } else {
            adState.adDialog?.dismiss()
        }

        nowAdEvent.adPrepareShow()

        LogEx.logDebug(adEvent.TAG, "needLoad=$needLoad")
        if (needLoad) {
            if (!adState.loadingAd) {
                LogEx.logDebug(adEvent.TAG, "inter adState !loadingAd")
                loadAd(activity, nowAdEvent) {
                    showReadyAd(activity, nowAdEvent)
                }
            } else {
                LogEx.logDebug(adEvent.TAG, "inter adState is loadingAd")
                loadingCallBack = {
                    showReadyAd(activity, nowAdEvent)
                }
            }
        } else {
            LogEx.logDebug(adEvent.TAG, "inter ad ready")
            showReadyAd(activity, nowAdEvent)
        }

    }


    private fun showReadyAd(ac: Activity, adEvent: AdEvent) {

//        val ac = adState.activityRef?.get()
        val admobEvent = (adEvent as AdmobEvent)
        val tag = adEvent.TAG

        LogEx.logDebug(tag, "showReadyAd ac=$ac currentAd=${adState.currentAd}")
        if (ac.isFinishing || ac.isDestroyed || adState.currentAd == null) {
            LogEx.logDebug(tag, "showReadyAd ac=null isFinishing isDestroyed")
            showCallBack?.failed()
            adState.onAdDisplayFailed()
            return
        }

        adState.currentAd?.run {

            fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {
                    super.onAdShowedFullScreenContent()

                    admobEvent.showAd(responseInfo, ac)

                    adState.onAdDisplayed()
                    showCallBack?.show()

                    LimitUtils.addDisplayNum()
                }

                override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                    super.onAdFailedToShowFullScreenContent(adError)

                    adState.onAdDisplayFailed()
                    showCallBack?.adFailed()
                    showCallBack = null

                    admobEvent.adShowError(adError)
                }

                override fun onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent()

                    adState.onAdHidden()

                    showCallBack?.close()
                    showCallBack = null
                    loadAd(MyApplication.appContext, AdmobEvent("interAd", "preload"))
                }

                override fun onAdClicked() {
                    super.onAdClicked()
                    admobEvent.clickAd(responseInfo)
                    //计数
                    LimitUtils.addClickNum()
                }
            }
//            val activity = adState.activityRef?.get()
            if (AdConfigBean.adsConfigBean.showCountdown) {
                createUICountdownTimer(adState.adDialog) {
                    show(ac)
                }
            } else {
                show(ac)
            }
        }
    }

    fun loadAd(
        context: Context,
        adEvent: AdEvent,
        loadCallBack: (() -> Unit)? = null
    ) {
        if (!adEvent.isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.INSERT, adEvent)) {
                this.showCallBack?.close(4)
                this.showCallBack = null
                adState.onAdLoadFailed()
                return
            }
        }

        //避免无效预加载
        if (adState.loadingAd && loadCallBack == null && loadingCallBack == null) {
            //容错机制
            adState.loadingAd = false
            return
        }

        adState.loadingAd = true
        adEvent.adPulStart()

        InterstitialAd.load(
            context, GlobalConfig.ID_ADMOB_INTER, AdRequest.Builder().build(),
            object : InterstitialAdLoadCallback() {
                override fun onAdLoaded(ad: InterstitialAd) {
                    adState.onAdLoaded(ad, adEvent)
                    loadCallBack?.invoke()

                    loadingCallBack?.invoke()
                    loadingCallBack = null

                    (adEvent as AdmobEvent).pullAd(ad.responseInfo)
                    LimitUtils.addRequestNum()
                    ad.onPaidEventListener = AdmobOnPaidEventListener(adEvent.scope)
                }

                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    adState.onAdLoadFailed()
                    if (loadCallBack != null) {
                        adState.onAdDisplayFailed()
                    }
                    showCallBack?.adFailed()
                    showCallBack = null
                    (adEvent as AdmobEvent).pullAd(loadAdError.responseInfo, loadAdError)

                }
            }
        )

    }


}