package autonomyic.polemicalic.congestionic.complementic.foldic

import android.app.Activity
import android.content.Context
import tooic.fatalityic.GlobalConfig
import tooic.fatalityic.Adventurousic
import autonomyic.polemicalic.congestionic.Aqueductic.createUICountdownTimer
import autonomyic.polemicalic.congestionic.Aqueductic.showAdCountDownDialog
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 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 java.lang.ref.WeakReference
import kotlin.div
import kotlin.text.get
import kotlin.text.toInt


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

    private var adState = Refrigerationic<InterstitialAd>()
    private var showCallBack: NASAic? = null

    fun show(
        activity: Activity,
        isUnLimit: Boolean,
        adEvent: Footprintic,
        showCallBack: NASAic? = null
    ) {

        if (activity.isFinishing || activity.isDestroyed) {
            showCallBack?.failed(0)
            adState.onAdDisplayFailed()
            return
        }

        if (!isUnLimit) {
            if (!Tumoric.isAdShow(Resignationic.INSERT, adEvent)) {
                showCallBack?.failed(2)
                return
            }
            if (Tumoric.isIntervalLimited(adEvent)) {
                showCallBack?.failed(3)
                return
            }
        }

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

    }

    private fun showReadyAd(adEvent: Footprintic) {

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

                    val ac = adState.activityRef?.get()
                    (adEvent as Epilepticic).showAd(responseInfo, ac)

                    adState.onAdDisplayed()
                    showCallBack?.show()

                    Tumoric.addDisplayNum()
                }

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

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

                    adEvent.adShowError(adError)
                }

                override fun onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent()

                    adState.onAdHidden()

                    showCallBack?.close()
                    showCallBack = null
                    loadAd(Adventurousic.appContext, Epilepticic("interAd", "preload"))
                }

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

    fun loadAd(
        context: Context,
        adEvent: Footprintic,
        isUnLimit: Boolean = false,
        isShow: Boolean = false,
    ) {
        if (!isUnLimit) {
            if (!Tumoric.isAdShow(Resignationic.INSERT, adEvent)) {
                this.showCallBack?.close(4)
                this.showCallBack = null
                adState.onAdLoadFailed()
                return
            }
        }

        adEvent.adPulStart()

        InterstitialAd.load(
            context, GlobalConfig.ID_ADMOB_INTER, AdRequest.Builder().build(),
            object : InterstitialAdLoadCallback() {
                override fun onAdLoaded(ad: InterstitialAd) {
                    adState.onAdLoaded(ad)
                    if (this@Juvenileic.showCallBack != null || isShow) {
                        showReadyAd(adEvent)
                    }
                    (adEvent as Epilepticic).pullAd(ad.responseInfo)
                    Tumoric.addRequestNum()
                    ad.onPaidEventListener = AdmobOnPaidEventListener(adEvent.scope)
                }

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

    }


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