package com.base.scanqrclear.ads.admob

import android.app.Activity
import android.content.Context
import com.base.scanqrclear.GlobalConfig
import com.base.scanqrclear.MyApplication
import com.base.scanqrclear.ads.AdDialog.showAdPreparingDialog
import com.base.scanqrclear.ads.AdEvent
import com.base.scanqrclear.ads.AdsShowCallBack
import com.base.scanqrclear.ads.AdsType
import com.base.scanqrclear.ads.LimitUtils
import com.base.scanqrclear.ads.AdState
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 AdInsertMgr {

    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(adState.lastShowTime, adEvent)) {
                showCallBack?.failed(3)
                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, isUnLimit, adEvent)
            }
        } 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?.googleFailed()
                    showCallBack = null

                    adEvent.adShowError(adError)
                }

                override fun onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent()

                    adState.onAdHidden()

                    showCallBack?.close()
                    showCallBack = null
                    loadAd(MyApplication.appContext, false, AdmobEvent("interAd", "preload"))
                }

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

    fun loadAd(
        context: Context,
        isUnLimit: Boolean,
        adEvent: AdEvent

    ) {
        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@AdInsertMgr.showCallBack != null) {
                        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?.googleFailed()
                    showCallBack = null
                }
            }
        )

    }


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