package com.base.appzxhy.business.ads.admob

import android.app.Activity
import android.content.Context
import com.base.appzxhy.GlobalConfig
import com.base.appzxhy.MyApplication
import com.base.appzxhy.business.ads.AdEvent
import com.base.appzxhy.business.ads.AdState
import com.base.appzxhy.business.ads.AdsShowCallBack
import com.base.appzxhy.business.ads.AdsType
import com.base.appzxhy.business.ads.LimitUtils
import com.base.appzxhy.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
import java.lang.ref.WeakReference


/**
 * 开屏广告加载显示管理类
 */
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,
        isUnLimit: Boolean,
        adEvent: AdEvent,
        showCallBack: AdsShowCallBack?
    ) {
        if (activity.isFinishing || activity.isDestroyed) {
            return
        }

        val nowAdEvent = adState.currentAdEvent ?: adEvent
        nowAdEvent.from = adEvent.from
        nowAdEvent.isUnLimit = isUnLimit

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

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

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

    private fun showReadyAd() {

        val ac = adState.activityRef?.get()
        if (ac == null || ac.isFinishing || ac.isDestroyed) {
            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()
                }
            }
            val activity = adState.activityRef?.get()
            activity?.let { show(it) }
        }
    }

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

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

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

        adState.loadingAd = true
        adState.currentAdEvent = adEvent
        adEvent.adPulStart()

        AppOpenAd.load(
            context,
            GlobalConfig.ID_ADMOB_OPEN,
            AdRequest.Builder().build(),
            object : AppOpenAd.AppOpenAdLoadCallback() {
                override fun onAdLoaded(appOpenAd: AppOpenAd) {
                    adState.onAdLoaded(appOpenAd, adEvent)

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

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

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

}