package com.base.locationsharewhite.ads.admob

import android.content.Context
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.base.locationsharewhite.helper.ConstConfig
import com.example.mydemo.strategy.ads.admob.NativeView
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdLoader
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdOptions
import java.util.concurrent.ConcurrentLinkedDeque

/**
 *原生广告加载显示管理类
 */
class AdNativeMgr {

    /**
     * 上一次的缓存成功时间
     */
    protected var lastTime: Long = 0

    /**
     * 原生广告缓存队列
     */
    private val cacheItems = ConcurrentLinkedDeque<NativeAd>()

    fun loadAd(context: Context, parent: ViewGroup? = null, layout: Int? = null) {
        val adLoader = AdLoader.Builder(
            context,
            ConstConfig.nativeAdId
        )
            .forNativeAd { nativeAd ->
                cacheItems.offer(nativeAd)
                lastTime = System.currentTimeMillis()
                if (parent != null && layout != null) show(parent, layout)
            }
            .withAdListener(object : AdListener() {
                override fun onAdFailedToLoad(error: LoadAdError) {

                }

                override fun onAdClicked() {
                    super.onAdClicked()
                }

                override fun onAdClosed() {
                    super.onAdClosed()
                }
            })
            .withNativeAdOptions(
                NativeAdOptions.Builder()
//                    .setAdChoicesPlacement(NativeAdOptions.ADCHOICES_TOP_RIGHT)
//                    .setMediaAspectRatio(NativeAdOptions.NATIVE_MEDIA_ASPECT_RATIO_SQUARE)
                    .build()
            )
            .build()
        // Load AdMob native advanced ads
        adLoader.loadAds(AdRequest.Builder().build(), 1)
    }

    fun show(parent: ViewGroup, layout: Int) {
        if (!LimitUtils.isAdShow()) {
            cacheItems.clear()
            return
        }
        val nativeAd = cacheItems.peek()
        if (nativeAd == null || !adAvailable()) {
            //缓存过期了就清空
            cacheItems.clear()
            loadAd(parent.context.applicationContext, parent, layout)
            return
        }
        NativeView(parent.context, layout).run {
            parent.removeAllViews()
            setNativeAd(nativeAd)
            parent.addView(this)
            parent.isVisible = true
        }
        loadAd(parent.context.applicationContext)
    }

    fun adAvailable(): Boolean {
        return ((System.currentTimeMillis() - lastTime) / 1000 / 60).toInt() < 30
    }
}