package com.base.locationsharewhite.ads.admob

import android.app.Activity
import android.content.Context
import com.base.locationsharewhite.GlobalConfig
import com.base.locationsharewhite.ads.AdEvent
import com.base.locationsharewhite.ads.AdsShowCallBack
import com.base.locationsharewhite.ads.AdsType
import com.base.locationsharewhite.ads.LimitUtils
import com.base.locationsharewhite.ads.adState
import com.base.locationsharewhite.helper.MyApplication
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
            }
        }

        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, isUnLimit, adEvent)
            }
        } 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?.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(MyApplication.appContext, false, 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, isUnLimit: Boolean, adEvent: AdEvent) {

        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?.googleFailed()
                    showCallBack = null
                    adState.onAdLoadFailed()
                    (adEvent as AdmobEvent).pullAd(loadAdError.responseInfo, loadAdError)
                }
            }
        )
    }

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