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 org.json.JSONObject
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Celledto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Driededto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Dishedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Slantedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Modestedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.cherryedto.ranchedto.gunedto.Refereeedto

object Breathedto {

    private val TAG = "AdMaxNativeUtils"
    private var nativeAdLoader: MaxNativeAdLoader = MaxNativeAdLoader(Celledto.nativeAdMaxId, Driededto.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) {
                    Dishedto.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)
                    Dishedto.logDebug(TAG, "onNativeAdLoadFailed")
                    val obj2 = JSONObject()
                    obj2.put("reason", "no_ad")
                    obj2.put("ad_unit", "nativeAd")
                    Slantedto.event("ad_show_error", ext = obj2)
                }

                override fun onNativeAdClicked(p0: MaxAd) {
                    super.onNativeAdClicked(p0)
                    Dishedto.logDebug(TAG, "onNativeAdClicked")
                    nativeAd?.let { Refereeedto.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.snakeedto)
//            .setTitleTextViewId(R.id.centraledto)
//            .setBodyTextViewId(R.id.spoiledto)
//            .setAdvertiserTextViewId(R.id.neglectedto)
//            .setIconImageViewId(R.id.eventedto)
//            .setMediaContentViewGroupId(R.id.tieedto)
//            .setOptionsContentViewGroupId(R.id.getedto)
//            .setStarRatingContentViewGroupId(R.id.sensitivityedto)
//            .setCallToActionButtonId(R.id.smileedto)
//            .build()
//        return MaxNativeAdView(binder, context)

        val binder: MaxNativeAdViewBinder = MaxNativeAdViewBinder.Builder(layout)
            .setTitleTextViewId(R.id.noredto)
            .setBodyTextViewId(R.id.typeedto)
//            .setAdvertiserTextViewId(R.id.neglectedto)
            .setIconImageViewId(R.id.graduateedto)
            .setMediaContentViewGroupId(R.id.chemistryedto)
//            .setOptionsContentViewGroupId(R.id.getedto)
//            .setStarRatingContentViewGroupId(R.id.sensitivityedto)
            .setCallToActionButtonId(R.id.elephantedto)
            .build()
        return MaxNativeAdView(binder, context)
    }


    fun showNativeAd(activity: Activity, parent: ViewGroup, layout: Int) {
        activityString = activity::class.java.toString().split(".").last()
        setNativeAdListener()
        if (!Modestedto.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 { Refereeedto.showAd(it, "nativeAd", activityString) }
                }
            }

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

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

    }

}