package com.base.locationsharewhite.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.locationsharewhite.ads.AdsShowCallBack
import com.base.locationsharewhite.ads.AdsType
import com.base.locationsharewhite.ads.BaseAdMgr
import com.base.locationsharewhite.ads.ConstConfig
import com.base.locationsharewhite.ads.admob.LimitUtils
import com.base.locationsharewhite.helper.EventUtils
import org.json.JSONObject
import java.lang.ref.WeakReference
import java.util.UUID

/**
 *插屏广告加载显示管理类
 */
class MaxInsertMgr : BaseAdMgr<MaxInterstitialAd>() {

    private var lastOpenDate: Long = 0

    override fun loadAd(context: Context, isUnLimit: Boolean) {
        if ((!loadingAd && LimitUtils.isAdShow(AdsType.INSERT)) || isUnLimit) {
            loadingAd = true
            //计数
            LimitUtils.addRequestNum()
            val reqId = UUID.randomUUID().toString()
            val obj = JSONObject()
            obj.put("req_id", reqId)
            obj.put("ad_type", "interAd")
            obj.put("from", context.javaClass.simpleName)
            EventUtils.event("ad_pull_start", ext = obj)

            currentAd = MaxInterstitialAd(ConstConfig.MAX_INSERT_UNIT_ID, context)
            currentAd?.setListener(object : MaxAdListener {
                override fun onAdLoaded(p0: MaxAd) {
//                    AdmobEvent.pullAd(ad.responseInfo, "interAd", reqId = reqId)
//                    ad.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(ad)
                    // 开屏广告加载成功
                    loadingAd = false
                    lastTime = System.currentTimeMillis()
                    val ac = activityRef?.get()
                    if (ac != null) {
                        show(ac, isUnLimit = isUnLimit)
                    }
                }

                override fun onAdDisplayed(p0: MaxAd) {
                }

                override fun onAdHidden(p0: MaxAd) {
                }

                override fun onAdClicked(p0: MaxAd) {
                }

                override fun onAdLoadFailed(p0: String, p1: MaxError) {
//                    AdmobEvent.pullAd(
//                        loadAdError.responseInfo,
//                        "interAd",
//                        loadAdError.message,
//                        reqId = reqId
//                    )
                    // 广告加载失败
                    // 官方不建议在此回调中重新加载广告
                    loadingAd = false
                    if (activityRef != null && !showingAd && showCallBack != null) {
                        showCallBack?.googleFailed()
                        showCallBack = null
                    }
                }

                override fun onAdDisplayFailed(p0: MaxAd, p1: MaxError) {
                }

            })
            currentAd?.loadAd()
        }
    }

    override fun show(activity: Activity, isUnLimit: Boolean, showCallBack: AdsShowCallBack?) {
        if (activity.isFinishing || activity.isDestroyed) {
            showCallBack?.failed()
            return
        }
        if (!LimitUtils.isAdShow(AdsType.INSERT)) {
            showCallBack?.failed()
            return
        }
        if (LimitUtils.isIntervalLimited(lastOpenDate)) {
            showCallBack?.failed()
            return
        }
        if (showingAd) {
            // 开屏广告正在展示
            return
        }
        if (showCallBack != null && this.showCallBack != showCallBack) this.showCallBack =
            showCallBack
        if ((currentAd?.isReady != true).also {
                if (it) {
                    val obj = JSONObject()
                    obj.put("reason", "no_ad")
                    obj.put("ad_unit", "interAd")
                    EventUtils.event("ad_show_error", ext = obj)
                }
            } || (!adAvailable()).also {
                if (it) {
                    val obj2 = JSONObject()
                    obj2.put("ad_unit", "interAd")
                    EventUtils.event("ad_expire", ext = obj2)
                }
            }) {
            //缓存广告过期
            currentAd = null
            if (activityRef == null) {
                activityRef = WeakReference(activity)
                // 开屏广告不可用或者缓存超时过期，重新加载
                loadAd(activity.applicationContext, isUnLimit)
            } else {
                activityRef = null
                this.showCallBack?.failed()
                this.showCallBack = null
                val obj = JSONObject()
                obj.put("reason", "no_ad")
                obj.put("ad_unit", "interAd")
                EventUtils.event("ad_show_error", ext = obj)
            }
            return
        }
        val obj1 = JSONObject()
        obj1.put("ad_unit", "interAd")
        EventUtils.event("ad_prepare_show", ext = obj1)
        currentAd?.run {
            setListener(object : MaxAdListener {
                override fun onAdLoaded(p0: MaxAd) {
                }

                override fun onAdDisplayed(p0: MaxAd) {
                    lastOpenDate = System.currentTimeMillis()
                    // 广告展示
                    currentAd = null
                    activityRef = null
                    this@MaxInsertMgr.showCallBack?.show()
                    // AdmobEvent.showAd(this@run.responseInfo, "interAd", activity)
                    //计数
                    LimitUtils.addDisplayNum()
                }

                override fun onAdHidden(p0: MaxAd) {
                    // 广告关闭，清空缓存数据，重新加载
                    showingAd = false

                    this@MaxInsertMgr.showCallBack?.close()
                    this@MaxInsertMgr.showCallBack = null
                    loadAd(activity.applicationContext)
                }

                override fun onAdClicked(p0: MaxAd) {
                    //  AdmobEvent.clickAd(this@run.responseInfo, "interAd")
                    //计数
                    LimitUtils.addClickNum()
                }

                override fun onAdLoadFailed(p0: String, p1: MaxError) {

                }

                override fun onAdDisplayFailed(p0: MaxAd, p1: MaxError) {
                    // 广告展示失败，清空缓存数据，重新加载
                    showingAd = false
                    currentAd = null
                    activityRef = null
                    this@MaxInsertMgr.showCallBack?.googleFailed()
                    this@MaxInsertMgr.showCallBack = null
                    val obj = JSONObject()
                    obj.put("reason", p1.message)
                    obj.put("code", p1.code)
                    obj.put("ad_unit", "interAd")
                    EventUtils.event("ad_show_error", ext = obj)
                }

            })
            showingAd = true
            showAd(activity)
        }
    }

    override fun adAvailable() = ((System.currentTimeMillis() - lastTime) / 1000 / 60).toInt() < 30
}