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.AdCountDownDialog.createUICountdownTimer
import com.base.appzxhy.business.ads.AdCountDownDialog.showAdCountDownDialog
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.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


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

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

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

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

        if (!isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.INSERT, adEvent)) {
                showCallBack?.failed(2)
                return
            }
            if (LimitUtils.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: AdEvent) {

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

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

                    adState.onAdDisplayed()
                    showCallBack?.show()

                    LimitUtils.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(MyApplication.appContext, AdmobEvent("interAd", "preload"))
                }

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

    fun loadAd(
        context: Context,
        adEvent: AdEvent,
        isUnLimit: Boolean = false,
        isShow: Boolean = false,
    ) {
        if (!isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.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@AdInterMgr.showCallBack != null || isShow) {
                        showReadyAd(adEvent)
                    }
                    (adEvent as AdmobEvent).pullAd(ad.responseInfo)
                    LimitUtils.addRequestNum()
                    ad.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(ad)
                }

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

    }


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