package com.base.appzxhy.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.ads.AdsType
import com.base.appzxhy.ads.AdDialog.showAdPreparingDialog
import com.base.appzxhy.ads.AdEvent
import com.base.appzxhy.ads.AdsShowCallBack
import com.base.appzxhy.ads.LimitUtils
import com.base.appzxhy.ads.adState
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 (adState.showingAd) {
            showCallBack?.failed(2)
            return
        }

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

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

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

            if (adState.currentAd?.isReady == false) {
                loadAd(activity, isUnLimit, adEvent)
                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?.googleFailed()
                    showCallBack = null

                    (adEvent as AdMaxEvent).adShowError(error)
                }

                override fun onAdHidden(p0: MaxAd) {

                    adState.onAdHidden()
                    showCallBack?.close()

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

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


            })
            setRevenueListener(AdMaxEvent.EventOnPaidEventListener())

            showAd(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()

            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?.googleFailed(5)
                    showCallBack = null
                }

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


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