package com.base.appzxhy.business.ads.admob

import android.app.Activity
import android.content.Context
import com.easy.clean.GlobalConfig
import com.easy.clean.MyApplication
import com.easy.clean.business.ads.AdEvent
import com.easy.clean.business.ads.AdState
import com.easy.clean.business.ads.AdsShowCallBack
import com.easy.clean.business.ads.AdsType
import com.easy.clean.business.ads.LimitUtils
import com.easy.clean.business.ads.admob.AdmobEvent
import com.easy.clean.business.ads.admob.AdmobOnPaidEventListener
import com.easy.clean.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, adEvent: AdEvent, showCallBack: AdsShowCallBack?) {
        if (activity.isFinishing || activity.isDestroyed) {
            return
        }
        if (!adEvent.isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.OPEN, adEvent)) {
                showCallBack?.failed()
                return
            }
            if (LimitUtils.isIntervalLimited(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) {
                    showReadyAd(adEvent)
                }
            }
        } else {
            showReadyAd(adEvent)
        }
    }

    private fun showReadyAd(adEvent: AdEvent) {

        val ac = adState.activityRef?.get()
        if (ac == null || ac.isFinishing || ac.isDestroyed) {
            LogEx.logDebug(TAG, "showReadyAd ac=null isFinishing isDestroyed")
            return
        }

        adState.currentAd?.run {
            fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {

                    (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,
        loadCallBack: (() -> Unit)? = null
    ) {

        if (!adEvent.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)
                    loadCallBack?.invoke()
                    (adEvent as AdmobEvent).pullAd(appOpenAd.responseInfo)
                    appOpenAd.onPaidEventListener = AdmobOnPaidEventListener(appOpenAd, adEvent.scope)
                    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
}