package com.base.appzxhy.business.ads.admob

import android.content.Context
import android.util.Log
import com.base.appzxhy.GlobalConfig
import com.base.appzxhy.MyApplication
import com.base.appzxhy.business.ads.AdsType
import com.base.appzxhy.business.ads.LimitUtils
import com.base.appzxhy.business.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 {

    private val TAG = "AdNativeMgr"

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

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

    fun loadAd(
        context: Context,
        admobEvent: AdmobEvent,
        showAction: ((ad: NativeAd) -> Unit)? = null
    ) {
        admobEvent.adPulStart()

        if (!LimitUtils.isAdShow(AdsType.NATIVE, admobEvent)) {
//            Log.e(TAG, "loadAd return")
            return
        }

        var currentNativeAd: NativeAd? = null

        val adLoader = AdLoader.Builder(
            context,
            GlobalConfig.ID_ADMOB_NATIVE
        ).forNativeAd { nativeAd ->

            lastTime = System.currentTimeMillis()
            nativeAd.setOnPaidEventListener(AdmobOnPaidEventListener(nativeAd, admobEvent.scope))
            currentNativeAd = nativeAd
            admobEvent.pullAd(nativeAd.responseInfo)


            if (showAction != null) {
                showAction.invoke(nativeAd)
            } else {
//                Log.e(TAG, "offer ad")
                cacheItems.offer(nativeAd)
            }

        }.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)) {
            Log.e(TAG, "!isAdShow")
            cacheItems.clear()
            return
        }
        Log.e(TAG, "adNative can show")

        if (!adAvailable()) {
            //缓存过期了就清空
            Log.e(TAG, "cacheItems clear")
            cacheItems.clear()
        }

        parent.isAdShowed = true
        val nativeAd = cacheItems.peek()
        if (nativeAd == null) {

            loadAd(parent.context, admobEvent) { ad ->
                Log.e(TAG, "load show")
                nativeCallBack?.invoke(ad)
                parent.setNativeAd(ad, layout)
                admobEvent.showAd(ad.responseInfo)

                loadAd(MyApplication.appContext, AdmobEvent("nativeAd", "preload"), null)
            }
        } else {

            val flag = cacheItems.remove(nativeAd)
            Log.e(TAG, "ready show remove=$flag size=${cacheItems.size}")

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


            loadAd(MyApplication.appContext, AdmobEvent("nativeAd", "preload"), null)
        }

    }

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