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 com.base.datarecovery.ads.AdDisplayUtils
import com.base.datarecovery.ads.admob.AdmobCommonUtils
import com.base.datarecovery.ads.max.AdMaxEvent
import com.base.datarecovery.help.BaseApplication
import com.base.datarecovery.help.ConfigHelper
import com.base.datarecovery.utils.EventUtils
import com.base.datarecovery.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()
                }

                override fun onNativeAdLoadFailed(p0: String, p1: MaxError) {
                    super.onNativeAdLoadFailed(p0, p1)
                    LogEx.logDebug(TAG, "onNativeAdLoadFailed")
                    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 showNativeAd(activity: Activity, parent: ViewGroup, layout: Int) {
        activityString = activity::class.java.toString().split(".").last()
        setNativeAdListener()
        if (!AdDisplayUtils.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 { AdMaxEvent.showAd(it, "nativeAd", activityString) }
                    AdDisplayUtils.getInstance().incrementAdDisplayCount()
                }
            }

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

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

    }

}