package com.base.appzxhy.ads.applovin

import android.widget.FrameLayout
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.applovin.mediation.nativeAds.MaxNativeAdViewBinder
import com.base.appzxhy.GlobalConfig
import com.base.appzxhy.R
import com.base.appzxhy.ads.AdsType
import com.base.appzxhy.ads.LimitUtils
import com.base.appzxhy.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: FrameLayout,
        @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: FrameLayout,
        @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)
        setMaxNativeAd(parent, layout)
        nativeCallBack?.invoke(nativeAd)
    }

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


    private fun setMaxNativeAd(parent: FrameLayout, layout: Int) {

//        val binder: MaxNativeAdViewBinder = MaxNativeAdViewBinder.Builder(R.layout.layout_max_native_custom)
//            .setTitleTextViewId(R.id.title_text_view)
//            .setBodyTextViewId(R.id.body_text_view)
//            .setAdvertiserTextViewId(R.id.advertiser_text_view)
//            .setIconImageViewId(R.id.icon_image_view)
//            .setMediaContentViewGroupId(R.id.media_view_container)
//            .setOptionsContentViewGroupId(R.id.options_view)
//            .setStarRatingContentViewGroupId(R.id.star_rating_view)
//            .setCallToActionButtonId(R.id.cta_button)
//            .build()
//        return MaxNativeAdView(binder, context)

        val binder: MaxNativeAdViewBinder = MaxNativeAdViewBinder.Builder(layout)
            .setTitleTextViewId(R.id.ad_headline)
            .setBodyTextViewId(R.id.ad_body)
//            .setAdvertiserTextViewId(R.id.advertiser_text_view)
            .setIconImageViewId(R.id.ad_app_icon)
            .setMediaContentViewGroupId(R.id.ad_media)
//            .setOptionsContentViewGroupId(R.id.options_view)
//            .setStarRatingContentViewGroupId(R.id.star_rating_view)
            .setCallToActionButtonId(R.id.ad_call_to_action)
            .build()
        val maxNativeAdView = MaxNativeAdView(binder, parent.context)
        parent.removeAllViews()
        parent.addView(maxNativeAdView)
    }
}