package com.base.scanqr.ads.admob

import android.app.Activity
import android.content.Context
import com.base.scanqr.GlobalConfig
import com.base.scanqr.ads.AdEvent
import com.base.scanqr.ads.AdsShowCallBack
import com.base.scanqr.ads.AdsType
import com.base.scanqr.ads.LimitUtils
import com.base.scanqr.ads.AdState
import com.base.scanqr.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.appopen.AppOpenAd
import java.lang.ref.WeakReference

/**
 * 开屏广告加载显示管理类
 */
class AdOpenMgr {

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


    fun show(activity: Activity, isUnLimit: Boolean, adEvent: AdEvent, showCallBack: AdsShowCallBack?) {
        if (activity.isFinishing || activity.isDestroyed) {
            return
        }
        if (!isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.OPEN, adEvent)) {
                showCallBack?.failed()
                return
            }
            if (LimitUtils.isIntervalLimited(adState.lastShowTime, adEvent)) {
                showCallBack?.failed()
                return
            }
        }
        if (adState.showingAd) {
            showCallBack?.failed()
            adEvent.adShowError("showingAd")
            adState.showingAd = false
            return
        }
        if (showCallBack != null) {
            this.showCallBack = showCallBack
            adState.activityRef = WeakReference(activity)
            adEvent.adPrepareShow()
        }

        if (!adState.loadingAd) {

            if (!adAvailable() || adState.currentAd == null) {
                loadAd(activity, isUnLimit, adEvent)
                return
            }
            showReadyAd(adEvent, activity)
        }


    }

    private fun showReadyAd(adEvent: AdEvent, activity: Activity) {
        LogEx.logDebug(TAG, "activity=$activity showReadyAd")
        adState.currentAd?.run {
            fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {

                    showCallBack?.show()

                    (adEvent as AdmobEvent).showAd(this@run.responseInfo, activity)
                    adState.onAdDisplayed()
                    //计数
                    LimitUtils.addDisplayNum()

                }

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

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

                    (adEvent as AdmobEvent).adShowError(adError)

                }

                override fun onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent()

                    showCallBack?.close()
                    showCallBack = null

                    adState.onAdHidden()

                    //预加载,“Timeout for show call succeed.”预加载的广告大概率,
                    loadAd(activity.applicationContext, false, AdmobEvent("openAd", "preload"))

                }

                override fun onAdClicked() {
                    (adEvent as AdmobEvent).clickAd(this@run.responseInfo)
                    //计数
                    LimitUtils.addClickNum()
                }
            }
            show(activity)
        }
    }

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

        if (!isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.OPEN, adEvent)) {
                this.showCallBack?.close()
                this.showCallBack = null
                return
            }
        }

        if (!adState.loadingAd) {
            adState.loadingAd = true
            adEvent.adPulStart()

            AppOpenAd.load(
                context,
                GlobalConfig.ID_ADMOB_OPEN,
                AdRequest.Builder().build(),
                object : AppOpenAd.AppOpenAdLoadCallback() {
                    override fun onAdLoaded(appOpenAd: AppOpenAd) {
                        adState.onAdLoaded(appOpenAd)
                        val ac = adState.activityRef?.get()
                        if (ac != null) {
                            show(ac, isUnLimit, adEvent, null)
                        }
                        (adEvent as AdmobEvent).pullAd(appOpenAd.responseInfo)
                        appOpenAd.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(appOpenAd)
                        LimitUtils.addRequestNum()

                    }

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

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