package com.base.locationsharewhite.ads.admob

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

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

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

    fun show(parent: ViewGroup) {
        if (adView != null) {
            adView?.destroy()
        }
        if (!LimitUtils.isAdShow()) {
            adView = null
            return
        }
        adView = AdView(parent.context)
        adView?.tag = "CollapsibleBannerAd"
        // val list = parent.children
//        list.forEach {
//            if (it.tag != "zhanweitu") {
//                parent.removeView(it)
//            }
//        }
        parent.addView(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 =
                if (BuildConfig.DEBUG) ConfigHelper.bannerAdmobIdTest else ConfigHelper.bannerAdmobId
            adView?.setAdSize(adSize)
            loadAd(parent)
            parent.viewTreeObserver.removeOnGlobalLayoutListener(listener)
        }
        parent.viewTreeObserver.addOnGlobalLayoutListener(listener)
    }


    fun loadAd(parent: ViewGroup) {
        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()
//                    val removeList = arrayListOf<View>()
//                    parent.children.forEach {
//                        if (it.tag != "CollapsibleBannerAd") {
//                            removeList.add(it)
//                        }
//                    }
//                    removeList.forEach {
//                        parent.removeView(it)
//                    }
                }
            }
        adView?.loadAd(adRequest)

    }
}