package com.tool.zxdemo.utils

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.annotation.LayoutRes
import com.applovin.mediation.MaxAd
import com.applovin.mediation.nativeAds.MaxNativeAdLoader
import com.applovin.mediation.nativeAds.MaxNativeAdView
import com.applovin.mediation.nativeAds.MaxNativeAdViewBinder
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdView
import com.swiftcleaner.chovey.R

class NativeView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null
) : FrameLayout(context, attrs) {

    fun setNativeAd(nativeAd: NativeAd, @LayoutRes resource: Int? = R.layout.layout_ad_native) {
        val adView =
            resource?.let { LayoutInflater.from(context).inflate(it, null) } as NativeAdView
        adView.mediaView = adView.findViewById(R.id.ad_media)
        adView.headlineView = adView.findViewById(R.id.ad_headline)
        adView.callToActionView = adView.findViewById(R.id.ad_call_to_action)
        adView.iconView = adView.findViewById(R.id.ad_icon)
        (adView.headlineView as TextView?)?.text = nativeAd.headline
        adView.mediaView!!.mediaContent = nativeAd.mediaContent
        if (nativeAd.callToAction != null) {
            (adView.callToActionView as TextView?)?.text = nativeAd.callToAction
        }

        if (nativeAd.icon != null) {
            (adView.iconView as ImageView?)?.setImageDrawable(nativeAd.icon!!.drawable)
        }

        adView.setNativeAd(nativeAd)
        removeAllViews()
        addView(adView)
    }

    fun setNativeAd(
        nativeAdLoader: MaxNativeAdLoader,
        nativeAd: MaxAd,
        @LayoutRes resource: Int = R.layout.native_custom_ad_view
    ) {
        val binder: MaxNativeAdViewBinder =
            MaxNativeAdViewBinder.Builder(resource)
                .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()
        val adView = MaxNativeAdView(binder, context)
        nativeAdLoader.render(adView, nativeAd)
        removeAllViews()
        addView(adView)
    }
}