package com.base.locationsharewhite.ads.admob

import android.app.Activity
import android.content.Context
import com.base.locationsharewhite.ads.AdEvent
import com.base.locationsharewhite.ads.AdsShowCallBack
import com.base.locationsharewhite.ads.AdsType
import com.base.locationsharewhite.ads.ConstConfig
import com.base.locationsharewhite.ads.LimitUtils
import com.base.locationsharewhite.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 (adState.showingAd) {
            showCallBack?.failed()
            adEvent.adShowError("showingAd")
            return
        }
        if (showCallBack != null) {
            this.showCallBack = showCallBack
            adState.activityRef = WeakReference(activity)
            adEvent.adPrepareShow()
        }

        if (!adState.loadingAd) {
            if (!isUnLimit) {
                if (!LimitUtils.isAdShow(AdsType.OPEN, adEvent)) {
                    showCallBack?.failed()
                    return
                }
                if (LimitUtils.isIntervalLimited(adState.lastShowTime, adEvent)) {
                    showCallBack?.failed()
                    return
                }
            }
            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.onAdDisplayed()

                    (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
                return
            }
        }

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

            AppOpenAd.load(
                context,
                ConstConfig.ADMOB_OPEN_UNIT_ID,
                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
}