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
import com.rgt.superr.business.ads.AdsType.Companion.INSERT


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

    private var adState = AdState<InterstitialAd>()
    private var showCallBack: AdsShowCallBack? = null


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

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

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

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

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


        val needLoad = adState.needLoad()
        this.showCallBack = showCallBack

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

        adEvent.adPrepareShow()

        LogEx.logDebug(adEvent.TAG, "needLoad=$needLoad")
        if (needLoad) {

            if (!adState.loadingAd) {
                LogEx.logDebug(adEvent.TAG, "inter adState !loadingAd")
                loadAd(activity, adEvent) {
                    if (it) {
                        showReadyAd(activity, adEvent)
                    } else {
                        showCallBack?.adFailed()
                    }
                }
            } else {
                LogEx.logDebug(adEvent.TAG, "inter adState is loadingAd")
                loadingCallBack = {
                    showReadyAd(activity, adEvent)
                }
            }
        } else {
            LogEx.logDebug(adEvent.TAG, "inter ad ready")
            showReadyAd(activity, adEvent)
        }

    }


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

        val admobEvent = (adEvent as AdmobEvent)
        val tag = adEvent.TAG

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

        adState.currentAd?.run {

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

                    adState.onAdDisplayed(INSERT)
                    showCallBack?.show()

                    LimitUtils.addDisplayNum()
                    admobEvent.showAd(responseInfo, ac)

                }

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

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

                    admobEvent.adShowError(adError)
                }

                override fun onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent()

                    adState.onAdHidden(INSERT)

                    showCallBack?.close()
                    showCallBack = null

                    loadAd(MyApplication.appContext, AdmobEvent("interAd", "preload"))
                }

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


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

        //避免无效预加载
        if (adState.loadingAd) {
            return
        }

        adEvent.adPulStart()
        adState.loadStart(adEvent)

        InterstitialAd.load(
            context, GlobalConfig.ID_ADMOB_INTER, AdRequest.Builder().build(),
            object : InterstitialAdLoadCallback() {
                override fun onAdLoaded(ad: InterstitialAd) {
                    val event = (adEvent as AdmobEvent)
                    ad.onPaidEventListener = AdmobOnPaidEventListener(ad, adEvent.scope)
                    adState.onAdLoaded(ad)

                    loadCallBack?.invoke(true)
                    loadingCallBack?.invoke(true)
                    loadingCallBack = null

                    LimitUtils.addRequestNum()
                    event.pullAd(ad.responseInfo)
                }

                override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                    adState.onAdLoadFailed()

                    if (loadCallBack != null) {
                        adState.onAdDisplayFailed()
                    }
                    loadCallBack?.invoke(false)
                    loadingCallBack?.invoke(false)
                    loadingCallBack = null

                    (adEvent as AdmobEvent).pullAd(loadAdError.responseInfo, loadAdError)

                }
            }
        )

    }


}
