package com.base.datarecovery.ads.admob

import android.content.Context
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import android.view.ViewTreeObserver
import com.base.datarecovery.BuildConfig
import com.base.datarecovery.help.ConfigHelper
import com.google.ads.mediation.admob.AdMobAdapter
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdSize
import com.google.android.gms.ads.AdView
import java.util.UUID

object AdmobBannerUtils {

    private var adView: AdView? = null
    private var listener: ViewTreeObserver.OnGlobalLayoutListener? = null

    fun showCollapsibleBannerAd(context: Context, parent: ViewGroup) {
        if (adView != null) {
            adView?.destroy()
        }
        adView = AdView(context)
        parent.removeAllViews()
        parent.addView(adView)
        listener = ViewTreeObserver.OnGlobalLayoutListener {
            val screenPixelDensity = context.resources.displayMetrics.density
            val adWidth = (parent.width / screenPixelDensity).toInt()
            val adSize = AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(context, adWidth)
            adView?.adUnitId = if (BuildConfig.DEBUG) ConfigHelper.bannerAdmobIdTest else ConfigHelper.bannerAdmobId
            adView?.setAdSize(adSize)
            loadCollapsibleBanner()
            parent.viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
        parent.viewTreeObserver.addOnGlobalLayoutListener(listener)
    }

    private fun loadCollapsibleBanner() {
        val extras = Bundle()
        extras.putString("collapsible", "bottom")
        extras.putString("collapsible_request_id", UUID.randomUUID().toString())
        val adRequest =
            AdRequest.Builder().addNetworkExtrasBundle(AdMobAdapter::class.java, extras).build()
        adView?.adListener =
            object : AdListener() {
                override fun onAdLoaded() {}
            }
        adView?.loadAd(adRequest)
    }

}