package com.tgv.malware.business.ads.admob

import android.app.Activity
import android.content.Context
import com.tgv.malware.GlobalConfig
import com.tgv.malware.MyApplication
import com.tgv.malware.business.ads.AdCountDownDialog.createUICountdownTimer
import com.tgv.malware.business.ads.AdCountDownDialog.showAdCountDownDialog
import com.tgv.malware.business.ads.AdEvent
import com.tgv.malware.business.ads.AdState
import com.tgv.malware.business.ads.AdsShowCallBack
import com.tgv.malware.business.ads.AdsType
import com.tgv.malware.business.ads.LimitUtils
import com.tgv.malware.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.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import java.lang.ref.WeakReference


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

    private val TAG = "AdInterMgr"
    private var adState = AdState<InterstitialAd>()
    private var showCallBack: AdsShowCallBack? = null

    //正在加载回调
    private var loadingCallBack: (() -> Unit)? = null

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

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

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

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


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

        if (adState.adDialog == null) {
            adState.adDialog = activity.showAdCountDownDialog()
        } else {
            adState.adDialog?.dismiss()
        }

        nowAdEvent.adPrepareShow()

        LogEx.logDebug(adEvent.TAG, "needLoad=$needLoad")
        if (needLoad) {
            if (!adState.loadingAd) {
                LogEx.logDebug(adEvent.TAG, "inter adState !loadingAd")
                loadAd(activity, adEvent) {
                    showReadyAd()
                }
            } else {
                LogEx.logDebug(adEvent.TAG, "inter adState is loadingAd")
                loadingCallBack = {
                    showReadyAd()
                }
            }
        } else {
            LogEx.logDebug(adEvent.TAG, "inter 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() {
                    super.onAdShowedFullScreenContent()

                    val ac = adState.activityRef?.get()
                    adEvent?.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?.clickAd(responseInfo)
                    //计数
                    LimitUtils.addClickNum()
                }
            }
            val activity = adState.activityRef?.get()
            activity?.let {
                createUICountdownTimer(adState.adDialog) {
                    show(it)
                }
            }
        }
    }

    fun loadAd(
        context: Context,
        adEvent: AdEvent,
        loadCallBack: (() -> Unit)? = null
    ) {
        if (!adEvent.isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.INSERT, adEvent)) {
                this.showCallBack?.close(4)
                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()

        InterstitialAd.load(
            context, GlobalConfig.ID_ADMOB_INTER, AdRequest.Builder().build(),
            object : InterstitialAdLoadCallback() {
                override fun onAdLoaded(ad: InterstitialAd) {
                    adState.onAdLoaded(ad, adEvent)
                    loadCallBack?.invoke()

                    loadingCallBack?.invoke()
                    loadingCallBack = null

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

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

    }


}