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.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.admob.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 var activityString: String = ""
    private fun setNativeAdListener() {
        if (!haveSetAdListener) {
            //加载展示监听
            nativeAdLoader.setNativeAdListener(object : MaxNativeAdListener() {
                override fun onNativeAdLoaded(nativeAdView: MaxNativeAdView?, ad: MaxAd) {
                    LogEx.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()
                    loadingListener = null
                }

                override fun onNativeAdLoadFailed(p0: String, p1: MaxError) {
                    super.onNativeAdLoadFailed(p0, p1)
                    loadingListener?.invoke()
                    loadingListener = null
                    LogEx.logDebug(TAG, "onNativeAdLoadFailed")
                    LogEx.logDebug(TAG, "code=${p1.code}")
                    LogEx.logDebug(TAG, "message=${p1.message}")
//                    AdDisplayUtils.getInstance().incrementAdRequestFailCount()
                    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)
                    LogEx.logDebug(TAG, "onNativeAdClicked")
//                    AdDisplayUtils.getInstance().incrementAdClickCount()
                    nativeAd?.let { AdMaxEvent.clickAd(it, "nativeAd") }
                    AdmobCommonUtils.isMultiClick(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.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()
        return MaxNativeAdView(binder, context)
    }

    fun loadNativeAd() {
        setNativeAdListener()
        if (!AdDisplayUtils.getInstance().shouldShowAd("nativeAd")) {
            return
        }
        nativeAdLoader.loadAd()
    }


    fun showNativeAd(activity: Activity, parent: ViewGroup, layout: Int) {
        activityString = activity::class.java.toString().split(".").last()
        LogEx.logDebug(TAG, "activityString=$activityString")
        setNativeAdListener()

        if (!AdDisplayUtils.getInstance().shouldShowAd("nativeAd")) {
            LogEx.logDebug(TAG, "!shouldShowAd")
            return
        }

        if (nativeAd?.nativeAd?.isExpired == true || nativeAd == null) {
            LogEx.logDebug(TAG, "nativeAd?.nativeAd?.isExpired == true")
            nativeAdLoader.destroy(nativeAd)
            nativeAdLoader.loadAd()
            loadingListener = {
                if (nativeAd != null) {
                    showReadyNative(activity, parent, layout)
                }
            }
        } else {
            showReadyNative(activity, parent, layout)
        }

    }

    private fun showReadyNative(activity: Activity, parent: ViewGroup, layout: Int) {
        val adView = createNativeAdView(activity, layout)

        LogEx.logDebug(TAG, "showReadNative adUnitId=${nativeAd?.adUnitId}")
        parent.isVisible = true
        parent.removeAllViews()
        nativeAdLoader.render(adView, nativeAd)
        parent.addView(adView)
        nativeAd?.let { AdMaxEvent.showAd(it, "nativeAd", activityString) }
//        AdDisplayUtils.getInstance().incrementAdDisplayCount()

        LogEx.logDebug(TAG, "loadingListener finish")
    }

}