package com.base.filerecoveryrecyclebin.ads.max

import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.adjust.sdk.Adjust
import com.adjust.sdk.AdjustAdRevenue
import com.adjust.sdk.AdjustConfig
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.filerecoveryrecyclebin.R
import com.base.filerecoveryrecyclebin.ads.AdDisplayUtils
import com.base.filerecoveryrecyclebin.ads.AdmobCommonUtils
import com.base.filerecoveryrecyclebin.help.BaseApplication
import com.base.filerecoveryrecyclebin.help.ConfigHelper
import com.base.filerecoveryrecyclebin.utils.EventUtils
import com.base.filerecoveryrecyclebin.utils.LogEx
import org.json.JSONObject

object AdMaxNativeUtils {

    private val TAG = "AdMaxNativeUtils"
    private var nativeAdLoader: MaxNativeAdLoader = MaxNativeAdLoader(ConfigHelper.nativeAdMaxId, BaseApplication.context)
    private var nativeAd: MaxAd? = null
    private var nativeLoadTime = Long.MAX_VALUE
    private var haveSetAdListener: Boolean = false
    private var loadingListener: (() -> Unit)? = null
    private fun setNativeAdListener() {
        if (!haveSetAdListener) {
            //加载展示监听
            nativeAdLoader.setNativeAdListener(object : MaxNativeAdListener() {
                override fun onNativeAdLoaded(nativeAdView: MaxNativeAdView?, ad: MaxAd) {
                    // Cleanup any pre-existing native ad to prevent memory leaks.
                    if (nativeAd != null) {
                        nativeAdLoader.destroy(nativeAd)
                    }

                    // Save ad to be rendered later.
                    nativeAd = ad
                    nativeLoadTime = System.currentTimeMillis()
                    loadingListener?.invoke()
                }

                override fun onNativeAdLoadFailed(p0: String, p1: MaxError) {
                    super.onNativeAdLoadFailed(p0, p1)
                    val obj2 = JSONObject()
                    obj2.put("reason", "no_ad")
                    obj2.put("ad_unit", "nativeAd")
                    EventUtils.event("ad_show_error", ext = obj2)


                }

                override fun onNativeAdClicked(p0: MaxAd) {
                    super.onNativeAdClicked(p0)
                    nativeAd?.let { AdMaxEvent.clickAd(it, "nativeAd") }
                    AdmobCommonUtils.isMultiClick(nativeAd)
                }

                override fun onNativeAdExpired(p0: MaxAd) {
                    super.onNativeAdExpired(p0)
                }
            })


            //广告价格监听
            nativeAdLoader.setRevenueListener { ad ->
                val adjustAdRevenue = AdjustAdRevenue(AdjustConfig.AD_REVENUE_APPLOVIN_MAX)
                adjustAdRevenue.setRevenue(ad.revenue, "USD")
                adjustAdRevenue.setAdRevenueNetwork(ad.networkName)
                adjustAdRevenue.setAdRevenueUnit(ad.adUnitId)
                adjustAdRevenue.setAdRevenuePlacement(ad.placement)
                Adjust.trackAdRevenue(adjustAdRevenue)
            }


            haveSetAdListener = true


        }
    }

    private fun createNativeAdView(context: Context): MaxNativeAdView {
        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)
    }


    fun showNativeAd(activity: Activity, parent: ViewGroup) {

        setNativeAdListener()

        val obj = JSONObject()
        obj.put("ad_unit", "NativeAd")
        EventUtils.event("ad_prepare_show", ext = obj)
        if (!AdDisplayUtils.getInstance().shouldShowAd()) {
            return
        }
        loadingListener = {
            if (System.currentTimeMillis() - nativeLoadTime <= 1000 * 60 * 60) {

                //是否已经加载渲染
                if (nativeAd?.nativeAd?.isExpired == true) {
                    nativeAdLoader.destroy(nativeAd)
                    nativeAdLoader.loadAd()
                } else {
                    //展示广告
                    val adView = createNativeAdView(activity)
                    parent.isVisible = true
                    nativeAdLoader.render(adView, nativeAd)
                    parent.addView(adView)
                    nativeAd?.let { AdMaxEvent.showAd(it, "nativeAd", activity) }
                }
            }

            loadingListener = null
            nativeAdLoader.loadAd()
            LogEx.logDebug(TAG, "loadingListener finish")
        }

        if (nativeAd == null) {
            nativeAdLoader.loadAd()
            val obj2 = JSONObject()
            obj2.put("reason", "no_ad")
            obj2.put("ad_unit", "nativeAd")
            EventUtils.event("ad_show_error", ext = obj2)
        } else {
            loadingListener?.invoke()
        }

    }

}