package com.base.filerecoveryrecyclebin.ads.admob

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.FrameLayout
import android.widget.TextView
import com.base.filerecoveryrecyclebin.R
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdView

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

    init {
        layoutParams = LayoutParams(
            ViewGroup.LayoutParams.MATCH_PARENT,
            ViewGroup.LayoutParams.WRAP_CONTENT
        )
    }

    fun setNativeAd(nativeAd: NativeAd?) {
        nativeAd ?: return

        val adView = LayoutInflater.from(context)
            .inflate(layout, this, false) as NativeAdView

        adView.mediaView = adView.findViewById(R.id.ad_media)
        adView.headlineView = adView.findViewById(R.id.ad_headline)
        adView.bodyView = adView.findViewById(R.id.ad_body)
        adView.callToActionView = adView.findViewById(R.id.ad_call_to_action)
        adView.iconView = adView.findViewById(R.id.ad_app_icon)
        (adView.headlineView as TextView?)?.text = nativeAd.headline
        adView.mediaView!!.mediaContent = nativeAd.mediaContent
        if (nativeAd.body == null) {
            adView.bodyView!!.visibility = View.INVISIBLE
        } else {
            adView.bodyView!!.visibility = View.VISIBLE
            (adView.bodyView as TextView?)?.text = nativeAd.body
        }
        if (nativeAd.callToAction == null) {
            adView.callToActionView!!.visibility = View.INVISIBLE
        } else {
            adView.callToActionView!!.visibility = View.VISIBLE
            (adView.callToActionView as Button?)?.text = nativeAd.callToAction
        }
//        if (nativeAd.icon == null) {
//            adView.iconView!!.visibility = View.GONE
//        } else {
//            (adView.iconView as ImageView?)?.setImageDrawable(
//                nativeAd.icon!!.drawable
//            )
//            adView.iconView!!.visibility = View.VISIBLE
//        }
        adView.setNativeAd(nativeAd)

        removeAllViews()
        addView(adView)
    }
}