import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import androidx.core.view.isVisible
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.datarecovery.R
import importantedto.admireedto.sweptedto.Monarchedto
import importantedto.admireedto.sweptedto.joinedto.Ubiquitousedto
import importantedto.afteredto.constitutionaledto.Interferenceedto
import importantedto.afteredto.constitutionaledto.Neckedto
import importantedto.gallonedto.Rideredto
import importantedto.gallonedto.Tumbleedto
import org.json.JSONObject

object Funeraledto {

    private val TAG = "AdMaxNativeUtils"
    private var nativeAdLoader: MaxNativeAdLoader = MaxNativeAdLoader(Neckedto.nativeAdMaxId, Interferenceedto.context)
    private var nativeAd: MaxAd? = null
    private var nativeLoadTime = Long.MAX_VALUE
    private var haveSetAdListener: Boolean = false
    private var loadingListener: (() -> Unit)? = null
    private var activityString: String = ""
    private fun setNativeAdListener() {
        if (!haveSetAdListener) {
            //加载展示监听
            nativeAdLoader.setNativeAdListener(object : MaxNativeAdListener() {
                override fun onNativeAdLoaded(nativeAdView: MaxNativeAdView?, ad: MaxAd) {
                    Tumbleedto.logDebug(TAG, "onNativeAdLoaded")
                    // Cleanup any pre-existing native ad to prevent memory leaks.
                    if (nativeAd?.nativeAd?.isExpired == true) {
                        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)
                    Tumbleedto.logDebug(TAG, "onNativeAdLoadFailed")
                    val obj2 = JSONObject()
                    obj2.put("reason", "no_ad")
                    obj2.put("ad_unit", "nativeAd")
                    Rideredto.event("ad_show_error", ext = obj2)
                }

                override fun onNativeAdClicked(p0: MaxAd) {
                    super.onNativeAdClicked(p0)
                    Tumbleedto.logDebug(TAG, "onNativeAdClicked")
                    nativeAd?.let { Ubiquitousedto.clickAd(it, "nativeAd") }
                }

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


            //广告价格监听
            nativeAdLoader.setRevenueListener { ad ->

            }


            haveSetAdListener = true


        }
    }

    private fun createNativeAdView(context: Context, layout: Int): MaxNativeAdView {

//        val binder: MaxNativeAdViewBinder = MaxNativeAdViewBinder.Builder(R.layout.setsedto)
//            .setTitleTextViewId(R.id.agencyedto)
//            .setBodyTextViewId(R.id.peanutedto)
//            .setAdvertiserTextViewId(R.id.loadedto)
//            .setIconImageViewId(R.id.aloudedto)
//            .setMediaContentViewGroupId(R.id.bundleedto)
//            .setOptionsContentViewGroupId(R.id.discloseedto)
//            .setStarRatingContentViewGroupId(R.id.continentedto)
//            .setCallToActionButtonId(R.id.railcaredto)
//            .build()
//        return MaxNativeAdView(binder, context)

        val binder: MaxNativeAdViewBinder = MaxNativeAdViewBinder.Builder(layout)
            .setTitleTextViewId(R.id.expertiseedto)
            .setBodyTextViewId(R.id.ifedto)
//            .setAdvertiserTextViewId(R.id.loadedto)
            .setIconImageViewId(R.id.primitiveedto)
            .setMediaContentViewGroupId(R.id.preferedto)
//            .setOptionsContentViewGroupId(R.id.discloseedto)
//            .setStarRatingContentViewGroupId(R.id.continentedto)
            .setCallToActionButtonId(R.id.driededto)
            .build()
        return MaxNativeAdView(binder, context)
    }


    fun showNativeAd(activity: Activity, parent: ViewGroup, layout: Int) {
        activityString = activity::class.java.toString().split(".").last()
        setNativeAdListener()
        if (!Monarchedto.getInstance().shouldShowAd("nativeAd")) {
            return
        }
        loadingListener = {
            if (System.currentTimeMillis() - nativeLoadTime <= 1000 * 60 * 60) {

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

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

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

    }

}