package com.base.appzxhy.ads.admob

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

/**
 * 开屏广告加载显示管理类
 */
class 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) {
        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()

                    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
                adState.onAdLoadFailed()
                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
}