package com.base.appzxhy.ads.admob

import android.view.LayoutInflater
import android.view.View
import android.widget.Button
import android.widget.FrameLayout
import android.widget.ImageView
import android.widget.TextView
import androidx.core.view.isVisible
import com.base.appzxhy.GlobalConfig
import com.base.appzxhy.R
import com.base.appzxhy.ads.AdsType
import com.base.appzxhy.ads.LimitUtils
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 com.google.android.gms.ads.nativead.NativeAdView
import java.util.concurrent.ConcurrentLinkedDeque

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

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

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

    private fun loadAd(
        admobEvent: AdmobEvent,
        parent: FrameLayout,
        nativeAdView: NativeAdView
    ) {
        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, nativeAdView)

        }.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,
        nativeParent: FrameLayout,
        nativeAdView: NativeAdView,
        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, nativeParent, nativeAdView)
            return
        }

        nativeCallBack?.invoke(nativeAd)

        //添加原生到父布局
        nativeParent.removeAllViews()
        nativeAdView.bindNativeAd(nativeAd)
        nativeParent.addView(nativeAdView)
        nativeParent.isVisible = true

        admobEvent.showAd(nativeAd.responseInfo)
    }

    private fun NativeAdView.bindNativeAd(nativeAd: NativeAd?) {
        nativeAd ?: return

        mediaView = findViewById(R.id.ad_media)
        headlineView = findViewById(R.id.ad_headline)
        bodyView = findViewById(R.id.ad_body)
        callToActionView = findViewById(R.id.ad_call_to_action)
        iconView = findViewById(R.id.ad_app_icon)

        (headlineView as TextView?)?.text = nativeAd.headline
        mediaView?.mediaContent = nativeAd.mediaContent
        if (nativeAd.body == null) {
            bodyView?.visibility = View.INVISIBLE
        } else {
            bodyView?.visibility = View.VISIBLE
            (bodyView as TextView?)?.text = nativeAd.body
        }
        if (nativeAd.callToAction == null) {
            callToActionView?.visibility = View.INVISIBLE
        } else {
            callToActionView?.visibility = View.VISIBLE
            (callToActionView as Button?)?.text = nativeAd.callToAction
        }
        if (nativeAd.icon == null) {
            iconView?.visibility = View.GONE
        } else {
            (iconView as ImageView?)?.setImageDrawable(
                nativeAd.icon?.drawable
            )
            iconView?.visibility = View.VISIBLE
        }
        setNativeAd(nativeAd)
    }

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

}