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.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.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
            }
        }

        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, adEvent, isUnLimit)
            }
        } else {
            showReadyAd(adEvent)
        }
    }

    private fun showReadyAd(adEvent: AdEvent) {

        adState.currentAd?.run {
            fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {
                    val ac = adState.activityRef?.get()
                    (adEvent as AdmobEvent).showAd(this@run.responseInfo, ac)

                    showCallBack?.show()

                    adState.onAdDisplayed()
                    //计数
                    LimitUtils.addDisplayNum()

                }

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

                    showCallBack?.adFailed()
                    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(MyApplication.appContext, AdmobEvent("openAd", "preload"))

                }

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

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

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


        adEvent.adPulStart()

        AppOpenAd.load(
            context,
            GlobalConfig.ID_ADMOB_OPEN,
            AdRequest.Builder().build(),
            object : AppOpenAd.AppOpenAdLoadCallback() {
                override fun onAdLoaded(appOpenAd: AppOpenAd) {
                    adState.onAdLoaded(appOpenAd)
                    if (this@AdOpenMgr.showCallBack != null) {
                        showReadyAd(adEvent)
                    }
                    (adEvent as AdmobEvent).pullAd(appOpenAd.responseInfo)
                    appOpenAd.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(appOpenAd)
                    LimitUtils.addRequestNum()

                }

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

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