package com.base.scanqr.ads.admob
import com.base.scanqr.GlobalConfig
import com.base.scanqr.ads.AdsType
import com.base.scanqr.ads.LimitUtils
import com.base.scanqr.ads.NativeParentView
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>()

    private fun loadAd(
        admobEvent: AdmobEvent,
        parent: NativeParentView,
        layout: Int
    ) {
        admobEvent.adPulStart()

        if (!LimitUtils.isAdShow(AdsType.NATIVE, admobEvent)) return

        var currentNativeAd: NativeAd? = null
        val adLoader = AdLoader.Builder(
            parent.context,
            GlobalConfig.ID_ADMOB_NATIVE
        ).forNativeAd { nativeAd ->
            currentNativeAd = nativeAd
            cacheItems.offer(nativeAd)
            lastTime = System.currentTimeMillis()
            nativeAd.setOnPaidEventListener(AdmobEvent.EventOnPaidEventListener(nativeAd))

            admobEvent.pullAd(nativeAd.responseInfo)
            show(admobEvent, parent, layout)

        }.withAdListener(object : AdListener() {

            override fun onAdFailedToLoad(error: LoadAdError) {
                admobEvent.pullAd(error.responseInfo, error)
            }

            override fun onAdClicked() {
                super.onAdClicked()
                admobEvent.clickAd(currentNativeAd?.responseInfo)
            }

            override fun onAdClosed() {
                super.onAdClosed()
            }
        }).withNativeAdOptions(
            NativeAdOptions.Builder()
                .build()
        ).build()
        adLoader.loadAds(AdRequest.Builder().build(), 1)
    }

    fun show(
        admobEvent: AdmobEvent,
        parent: NativeParentView,
        layout: Int,
        nativeCallBack: ((Any?) -> Unit)? = null
    ) {

        admobEvent.adPrepareShow()

        if (!LimitUtils.isAdShow(AdsType.NATIVE, admobEvent)) {
            cacheItems.clear()
            return
        }

        val nativeAd = cacheItems.peek()
        if (nativeAd == null || !adAvailable()) {
            //缓存过期了就清空
            cacheItems.clear()
            loadAd(admobEvent, parent, layout)
            return
        }

        nativeCallBack?.invoke(nativeAd)
        parent.setNativeAd(nativeAd, layout)
        admobEvent.showAd(nativeAd.responseInfo)
    }

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