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.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.appopen.AppOpenAd


/**
 * 开屏广告加载显示管理类
 */
class AdOpenMgr {

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

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

    fun show(
        activity: Activity,
        adEvent: AdEvent,
        showCallBack: AdsShowCallBack?
    ) {
        if (activity.isFinishing || activity.isDestroyed) {
            return
        }

        val nowAdEvent = adEvent
        adState.currentAdEvent?.let { nowAdEvent.reqId = it.reqId }

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

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

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

    private fun showReadyAd(ac: Activity) {

//        val ac = adState.activityRef?.get()
        if (ac.isFinishing || ac.isDestroyed || adState.currentAd == null) {
            LogEx.logDebug(TAG, "showReadyAd ac=null isFinishing isDestroyed")
            return
        }

        adState.currentAd?.run {

            val adEvent = adState.currentAdEvent as AdmobEvent?

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

                    adEvent?.showAd(this@run.responseInfo, ac)

                    showCallBack?.show()

                    adState.onAdDisplayed()
                    //计数
                    LimitUtils.addDisplayNum()

                }

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

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

                    adEvent?.adShowError(adError)

                }

                override fun onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent()

                    showCallBack?.close()
                    showCallBack = null

                    adState.onAdHidden()

                    //预加载,“Timeout for show call succeed.”预加载的广告大概率,
                    loadAd(MyApplication.appContext, AdmobEvent("openAd", "preload"))

                }

                override fun onAdClicked() {
                    adEvent?.clickAd(this@run.responseInfo)
                    //计数
                    LimitUtils.addClickNum()
                }
            }
            show(ac)
        }
    }

    fun loadAd(
        context: Context,
        adEvent: AdEvent,
        loadCallBack: (() -> Unit)? = null
    ) {

        if (!adEvent.isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.OPEN, adEvent)) {
                this.showCallBack?.failed()
                this.showCallBack = null
                adState.onAdLoadFailed()
                return
            }
        }

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

        adState.loadingAd = true
        adEvent.adPulStart()

        AppOpenAd.load(
            context,
            GlobalConfig.ID_ADMOB_OPEN,
            AdRequest.Builder().build(),
            object : AppOpenAd.AppOpenAdLoadCallback() {
                override fun onAdLoaded(appOpenAd: AppOpenAd) {
                    val event = (adEvent as AdmobEvent)
                    appOpenAd.onPaidEventListener = AdmobOnPaidEventListener(appOpenAd, adEvent.scope)

                    adState.onAdLoaded(appOpenAd, adEvent)

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

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

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

}