package com.easy.clean.business.ads.applovin

import androidx.annotation.LayoutRes
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxError
import com.applovin.mediation.nativeAds.MaxNativeAdListener
import com.applovin.mediation.nativeAds.MaxNativeAdLoader
import com.applovin.mediation.nativeAds.MaxNativeAdView
import com.easy.clean.GlobalConfig
import com.easy.clean.business.ads.AdsType
import com.easy.clean.business.ads.LimitUtils
import com.easy.clean.business.ads.NativeParentView
import com.easy.clean.business.helper.EventUtils
import org.json.JSONObject
import java.util.UUID

/**
 *原生广告加载显示管理类
 */
class MaxNativeMgr {

    /**
     * 上一次的缓存成功时间
     */
    protected var lastTime: Long = 0

    /**
     * 原生广告
     */
    private var currentAd: MaxAd? = null
    private var currentLoader: MaxNativeAdLoader? = null


    private fun loadAd(
        adMaxEvent: AdMaxEvent,
        parent: NativeParentView,
        @LayoutRes layout: Int
    ) {

        if (!LimitUtils.isAdShow(AdsType.NATIVE, adMaxEvent)) return

        val reqId = UUID.randomUUID().toString()
        val obj = JSONObject()
        obj.put("req_id", reqId)
        obj.put("ad_type", "nativeAd")

        val nativeAdLoader = MaxNativeAdLoader(GlobalConfig.ID_MAX_NATIVE, parent.context)

        nativeAdLoader.setNativeAdListener(object : MaxNativeAdListener() {

            override fun onNativeAdLoaded(nativeAdView: MaxNativeAdView?, ad: MaxAd) {
                currentLoader = nativeAdLoader
                currentAd = ad
                lastTime = System.currentTimeMillis()
                adMaxEvent.pullAd(ad)
                nativeAdLoader.setRevenueListener(AdMaxEvent.EventOnPaidEventListener())
                show(adMaxEvent, parent, layout)
            }

            override fun onNativeAdLoadFailed(adUnitId: String, error: MaxError) {
                adMaxEvent.pullAd(null, error)
            }

            override fun onNativeAdClicked(ad: MaxAd) {

            }

        })
        nativeAdLoader.loadAd()
    }

    fun show(
        adMaxEvent: AdMaxEvent,
        parent: NativeParentView,
        @LayoutRes layout: Int,
        nativeCallBack: ((Any?) -> Unit)? = null
    ) {
        if (!LimitUtils.isAdShow(AdsType.NATIVE, adMaxEvent)) {
            currentLoader = null
            currentAd = null
            return
        }
        val nativeAd = currentAd
        val nativeLoader = currentLoader
        if ((nativeAd == null || nativeLoader == null).also {
                if (it) {
                    val obj2 = JSONObject()
                    obj2.put("reason", "no_ad")
                    obj2.put("ad_unit", "nativeAd")
                    EventUtils.event("ad_show_error", ext = obj2)
                }
            } || (!adAvailable()).also {
                if (it) {
                    val obj2 = JSONObject()
                    obj2.put("ad_unit", "nativeAd")
                    EventUtils.event("ad_expire", ext = obj2)
                }
            }) {
            //缓存过期了就清空
            currentLoader = null
            currentAd = null
            loadAd(AdMaxEvent("nativeAd", "preload"), parent, layout)
            return
        }
        val obj = JSONObject()
        obj.put("ad_unit", "nativeAd")
        EventUtils.event("ad_prepare_show", ext = obj)
        parent.setNativeAd(nativeLoader!!, nativeAd!!, layout)
        nativeCallBack?.invoke(nativeAd)
    }

    private fun adAvailable(): Boolean {
        return ((System.currentTimeMillis() - lastTime) / 1000 / 60).toInt() < 30
    }
}