package com.base.appzxhy.business.ads.applovin

import android.app.Activity
import android.content.Context
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxInterstitialAd
import com.base.appzxhy.GlobalConfig
import com.base.appzxhy.business.ads.AdCountDownDialog.showAdCountDownDialog
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 java.lang.ref.WeakReference

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

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

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

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

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

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

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

            if (adState.currentAd?.isReady == false) {
                loadAd(activity, adEvent, isUnLimit)
                return
            }
            showReadyAd(adEvent)
        }

    }


    private fun showReadyAd(adEvent: AdEvent) {
        adState.currentAd?.run {
            setListener(object : MaxAdListener {
                override fun onAdLoaded(p0: MaxAd) = Unit
                override fun onAdLoadFailed(p0: String, p1: MaxError) = Unit

                override fun onAdDisplayed(ad: MaxAd) {

                    adState.onAdDisplayed()
                    showCallBack?.show()

                    (adEvent as AdMaxEvent).showAd(ad, activity::class.simpleName)
                    //计数
                    LimitUtils.addDisplayNum()
                }

                override fun onAdDisplayFailed(ad: MaxAd, error: MaxError) {
                    adState.onAdDisplayFailed()
                    showCallBack?.adFailed()
                    showCallBack = null

                    (adEvent as AdMaxEvent).adShowError(error)
                }

                override fun onAdHidden(p0: MaxAd) {

                    adState.onAdHidden()
                    showCallBack?.close()

                    loadAd(activity.applicationContext, AdMaxEvent("interAd", "preload"))
                }

                override fun onAdClicked(ad: MaxAd) {
                    (adEvent as AdMaxEvent).clickAd(ad)
                    //计数
                    LimitUtils.addClickNum()
                }


            })
            setRevenueListener(AdMaxEvent.EventOnPaidEventListener())

            showAd(activity)
        }
    }


    fun loadAd(
        context: Context,
        adEvent: AdEvent,
        isUnLimit: Boolean = false,
    ) {
        if (!isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.INSERT, adEvent)) {
                this.showCallBack?.close(4)
                this.showCallBack = null
                return
            }
        }

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

            adEvent.adPulStart()

            adState.currentAd = MaxInterstitialAd(GlobalConfig.ID_MAX_INTER, context)
            adState.currentAd?.setListener(object : MaxAdListener {

                override fun onAdDisplayed(p0: MaxAd) = Unit
                override fun onAdHidden(p0: MaxAd) = Unit
                override fun onAdClicked(p0: MaxAd) = Unit
                override fun onAdDisplayFailed(p0: MaxAd, p1: MaxError) = Unit

                override fun onAdLoaded(ad: MaxAd) {
                    adState.onAdLoaded(null)
                    val ac = adState.activityRef?.get()
                    if (ac != null) {
                        show(ac, isUnLimit, adEvent, null)
                    }

                    (adEvent as AdMaxEvent).pullAd(ad)
                    LimitUtils.addRequestNum()
                }

                override fun onAdLoadFailed(ad: String, error: MaxError) {
                    adState.onAdLoadFailed()

                    (adEvent as AdMaxEvent).pullAd(null, error)

                    showCallBack?.adFailed(5)
                    showCallBack = null
                }

            })
            adState.currentAd?.loadAd()
        }
    }


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