package com.base.locationsharewhite.ads.admob

import android.os.Bundle
import android.view.ViewGroup
import android.view.ViewTreeObserver
import com.base.locationsharewhite.ads.AdsType
import com.base.locationsharewhite.helper.config.ConstConfig
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

/**
 *banner广告加载显示管理类
 */
class AdBannerMgr {

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

    fun show(parent: ViewGroup, adClose: (() -> Unit)? = null) {

        if (!LimitUtils.isAdShow(AdsType.BANNER)) {
            adView = null
            return
        }

        parent.removeAllViews()

        adView?.destroy()
        adView = null

        adView = AdView(parent.context)
        parent.addView(adView)
        adView?.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(adView)

        listener = ViewTreeObserver.OnGlobalLayoutListener {
            val screenPixelDensity = parent.context.resources.displayMetrics.density
            val adWidth = (parent.width / screenPixelDensity).toInt()
            val adSize =
                AdSize.getCurrentOrientationAnchoredAdaptiveBannerAdSize(parent.context, adWidth)
            adView?.adUnitId = ConstConfig.bannerAdId
            adView?.setAdSize(adSize)
            loadAd(adClose)
            parent.viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
        parent.viewTreeObserver.addOnGlobalLayoutListener(listener)
    }


    fun loadAd(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() {

                }

                override fun onAdOpened() {

                }

                override fun onAdClosed() {
                    super.onAdClosed()
                    adClose?.invoke()
                }
            }
        adView?.loadAd(adRequest)

    }
}