package com.base.pdfreaderallpdfreader.ads.admob

import android.content.Context
import android.os.Bundle
import android.view.ViewGroup
import android.view.ViewTreeObserver
import com.base.pdfreaderallpdfreader.BuildConfig
import com.base.pdfreaderallpdfreader.helper.ConfigHelper
import com.base.pdfreaderallpdfreader.utils.AppPreferences
import com.base.pdfreaderallpdfreader.utils.LogEx
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 const val TAG = "AdmobBannerUtils"
    private var adView: AdView? = null
    private var listener: ViewTreeObserver.OnGlobalLayoutListener? = null

    fun showCollapsibleBannerAd(context: Context, parent: ViewGroup, adClose: (() -> Unit)? = null) {
        val isShowBanner = AppPreferences.getInstance().getString("isShowBanner", "0").toInt()
        if (isShowBanner == 0) {
            return
        }

        parent.removeAllViews()

        adView?.destroy()
        adView = null

        adView = AdView(context)
        parent.addView(adView)
        adView?.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(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(adClose)
            parent.viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
        parent.viewTreeObserver.addOnGlobalLayoutListener(listener)
    }

    private fun loadCollapsibleBanner(adClose: (() -> Unit)?) {

        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() {
                    LogEx.logDebug(TAG, "onAdLoaded")
                }

                override fun onAdOpened() {
                    LogEx.logDebug(TAG, "onAdOpened")
                }

                override fun onAdClosed() {
                    super.onAdClosed()
                    LogEx.logDebug(TAG, "onAdClosed")
                    adClose?.invoke()
                }
            }
        adView?.loadAd(adRequest)
    }

}