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.MaxAppOpenAd
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 MaxOpenMgr : BaseAdMgr<MaxAppOpenAd>() {

    private var lastOpenDate: Long = 0

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

            currentAd = MaxAppOpenAd(ConstConfig.MAX_OPEN_UNIT_ID, context)
            currentAd?.setListener(object : MaxAdListener {
                override fun onAdLoaded(p0: MaxAd) {
                    loadingAd = false
                    lastTime = System.currentTimeMillis()
                    val ac = activityRef?.get()
                    if (ac != null) {
                        show(ac, isUnLimit = isUnLimit)
                    }
//                    AdmobEvent.pullAd(appOpenAd.responseInfo, "openAd", reqId = reqId)
//                    appOpenAd.onPaidEventListener =
//                        AdmobEvent.EventOnPaidEventListener(appOpenAd)
                }

                override fun onAdDisplayed(p0: MaxAd) {

                }

                override fun onAdHidden(p0: MaxAd) {

                }

                override fun onAdClicked(p0: MaxAd) {
                }

                override fun onAdLoadFailed(p0: String, p1: MaxError) {
                    loadingAd = false
                    if (activityRef != null && !showingAd && showCallBack != null) {
                        showCallBack?.googleFailed()
                        showCallBack = null
                    }
//                    AdmobEvent.pullAd(
//                        loadAdError.responseInfo,
//                        "openAd",
//                        loadAdError.message,
//                        reqId = reqId
//                    )
                }

                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 (!isUnLimit) {
            if (!LimitUtils.isAdShow(AdsType.OPEN)) {
                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", "openAd")
                    EventUtils.event("ad_show_error", ext = obj)
                }
            } || (!adAvailable()).also {
                if (it) {
                    val obj2 = JSONObject()
                    obj2.put("ad_unit", "openAd")
                    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", "openAd")
                EventUtils.event("ad_show_error", ext = obj)
            }
            return
        }
        val obj1 = JSONObject()
        obj1.put("ad_unit", "openAd")
        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@MaxOpenMgr.showCallBack?.show()
                    //计数
                    LimitUtils.addDisplayNum()
                    // AdmobEvent.showAd(this@run.responseInfo, "openAd", activity)
                }

                override fun onAdHidden(p0: MaxAd) {
                    // 广告关闭，清空缓存数据，重新加载
                    showingAd = false
                    this@MaxOpenMgr.showCallBack?.close()
                    this@MaxOpenMgr.showCallBack = null
                    loadAd(activity.applicationContext)
                }

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

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

                }

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

            })
            showingAd = true
            showAd()
        }
    }

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