package com.base.locationsharewhite.ads.admob

import android.app.Activity
import android.content.Context
import com.base.locationsharewhite.ads.AdDialog.showAdPreparingDialog
import com.base.locationsharewhite.ads.AdEvent
import com.base.locationsharewhite.ads.AdsShowCallBack
import com.base.locationsharewhite.ads.AdsType
import com.base.locationsharewhite.ads.ConstConfig.ADMOB_INSERT_UNIT_ID
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.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import java.lang.ref.WeakReference

/**
 *插屏广告加载显示管理类
 */
class AdInsertMgr {

    private var adState = adState<InterstitialAd>()
    private var showCallBack: AdsShowCallBack? = null

    fun show(activity: Activity, isUnLimit: Boolean, adEvent: AdEvent, showCallBack: AdsShowCallBack?) {

        if (activity.isFinishing || activity.isDestroyed) {
            showCallBack?.failed(0)
            return
        }
        if (adState.showingAd) {
            showCallBack?.failed(1)
            return
        }

        if (showCallBack != null) {
            this.showCallBack = showCallBack
            adState.activityRef = WeakReference(activity)
            if (adState.adDialog == null) {
                adState.adDialog = activity.showAdPreparingDialog(1)
            }
            adEvent.adPrepareShow()
        }

        if (!adState.loadingAd) {

            if (!isUnLimit) {
                if (!LimitUtils.isAdShow(AdsType.INSERT, adEvent)) {
                    showCallBack?.failed(2)
                    return
                }
                if (LimitUtils.isIntervalLimited(adState.lastShowTime, adEvent)) {
                    showCallBack?.failed(3)
                    return
                }
            }

            if (adState.currentAd == null) {
                loadAd(activity, isUnLimit, adEvent)
                return
            }
            if (!adAvailable()) {
                loadAd(activity, isUnLimit, adEvent)
                return
            }
            showReadyAd(adEvent, activity)
        }
    }

    private fun showReadyAd(adEvent: AdEvent, activity: Activity) {
        adState.currentAd?.run {
            fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {
                    super.onAdShowedFullScreenContent()
                    adState.onAdDisplayed()
                    showCallBack?.show()
                    (adEvent as AdmobEvent).showAd(responseInfo, activity)
                    LimitUtils.addDisplayNum()
                }

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

                    adState.onAdDisplayFailed()
                    showCallBack?.googleFailed()
                    showCallBack = null

                    adEvent.adShowError(adError)
                }

                override fun onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent()

                    adState.onAdHidden()

                    showCallBack?.close()
                    showCallBack = null
                    loadAd(activity.applicationContext, false, AdmobEvent("interAd", "preload"))
                }

                override fun onAdClicked() {
                    super.onAdClicked()
                    (adEvent as AdmobEvent).clickAd(responseInfo)
                    //计数
                    LimitUtils.addClickNum()
                }
            }
            show(activity)
        }
    }

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

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

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

            adEvent.adPulStart()

            InterstitialAd.load(context, ADMOB_INSERT_UNIT_ID, AdRequest.Builder().build(),
                object : InterstitialAdLoadCallback() {
                    override fun onAdLoaded(ad: InterstitialAd) {
                        adState.onAdLoaded(ad)
                        val ac = adState.activityRef?.get()
                        if (ac != null) {
                            show(ac, isUnLimit, adEvent, null)
                        }
                        (adEvent as AdmobEvent).pullAd(ad.responseInfo)
                        LimitUtils.addRequestNum()
                        ad.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(ad)
                    }

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

    }


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