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

import android.app.Activity
import android.content.Context
import tooic.fatalityic.GlobalConfig
import tooic.fatalityic.Adventurousic
import autonomyic.polemicalic.congestionic.Footprintic
import autonomyic.polemicalic.congestionic.Refrigerationic
import autonomyic.polemicalic.congestionic.NASAic
import autonomyic.polemicalic.congestionic.Resignationic
import autonomyic.polemicalic.congestionic.Tumoric
import autonomyic.polemicalic.congestionic.complementic.foldic.Epilepticic
import autonomyic.polemicalic.congestionic.complementic.foldic.AdmobOnPaidEventListener
import tooic.fatalityic.redic.speckledic.hankeringic.Upholsteryic
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 Predestinationic {

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


    fun show(activity: Activity, adEvent: Footprintic, showCallBack: NASAic?) {
        if (activity.isFinishing || activity.isDestroyed) {
            return
        }
        if (!adEvent.isUnLimit) {
            if (!Tumoric.isAdShow(Resignationic.OPEN, adEvent)) {
                showCallBack?.failed()
                return
            }
            if (Tumoric.isIntervalLimited(adEvent)) {
                showCallBack?.failed()
                return
            }
        }

        adEvent.adPrepareShow()
        adState.activityRef = WeakReference(activity)
        this.showCallBack = showCallBack
//        if (adState.adDialog == null) {
//            adState.adDialog = activity.showAdPreparingDialog(1)
//        } else {
//            adState.adDialog?.dismiss()
//        }
        val needLoad = adState.currentAd == null || !adAvailable()
        if (needLoad) {
            if (!adState.loadingAd) {
                loadAd(activity, adEvent) {
                    showReadyAd(adEvent)
                }
            }
        } else {
            showReadyAd(adEvent)
        }
    }

    private fun showReadyAd(adEvent: Footprintic) {

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

        adState.currentAd?.run {
            fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {

                    (adEvent as Epilepticic).showAd(this@run.responseInfo, ac)

                    showCallBack?.show()

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

                }

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

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

                    (adEvent as Epilepticic).adShowError(adError)

                }

                override fun onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent()

                    showCallBack?.close()
                    showCallBack = null

                    adState.onAdHidden()

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

                }

                override fun onAdClicked() {
                    (adEvent as Epilepticic).clickAd(this@run.responseInfo)
                    //计数
                    Tumoric.addClickNum()
                }
            }
            val activity = adState.activityRef?.get()
            activity?.let { show(it) }
        }
    }

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

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

        adEvent.adPulStart()

        AppOpenAd.load(
            context,
            GlobalConfig.ID_ADMOB_OPEN,
            AdRequest.Builder().build(),
            object : AppOpenAd.AppOpenAdLoadCallback() {
                override fun onAdLoaded(appOpenAd: AppOpenAd) {
                    adState.onAdLoaded(appOpenAd)
                    loadCallBack?.invoke()
                    (adEvent as Epilepticic).pullAd(appOpenAd.responseInfo)
                    appOpenAd.onPaidEventListener = AdmobOnPaidEventListener(appOpenAd, adEvent.scope)
                    Tumoric.addRequestNum()
                }

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

    private fun adAvailable() = ((System.currentTimeMillis() - adState.lastLoadTime) / 1000 / 60).toInt() < 30
}