package com.base.appzxhy.ads.admob

import android.content.Context
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 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.MediaView
import com.google.android.gms.ads.nativead.NativeAd
import com.google.android.gms.ads.nativead.NativeAdOptions
import com.google.android.gms.ads.nativead.NativeAdView

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

    private val TAG = this::class.java.simpleName
    protected var lastTime: Long = 0
    private var currentAd: NativeAd? = null

    private fun loadAd(
        admobEvent: AdmobEvent,
        context: Context,
        callback: ((nativeAd: NativeAd) -> Unit)? = null
    ) {

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

        admobEvent.adPulStart()

        var currentNativeAd: NativeAd? = null
        val adLoader = AdLoader.Builder(
            context,
            GlobalConfig.ID_ADMOB_NATIVE
        ).forNativeAd { nativeAd ->
            currentNativeAd = nativeAd
            lastTime = System.currentTimeMillis()
            nativeAd.setOnPaidEventListener(AdmobEvent.EventOnPaidEventListener(nativeAd))
            admobEvent.pullAd(nativeAd.responseInfo)
            callback?.invoke(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: FrameLayout,
        layout: Int,
        nativeCallBack: ((Any?) -> Unit)? = null
    ) {

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

        admobEvent.adPrepareShow()

        if (currentAd == null || !adAvailable()) {
            loadAd(admobEvent, parent.context) { nativeAd: NativeAd ->
                setNative(parent, layout, nativeAd)
                admobEvent.showAd(nativeAd.responseInfo)
                nativeCallBack?.invoke(nativeAd)
            }
        } else {
            currentAd?.let {
                setNative(parent, layout, it)
                admobEvent.showAd(it.responseInfo)
                nativeCallBack?.invoke(it)
            }
        }
    }

    private fun setNative(parent: FrameLayout, layout: Int, nativeAd: NativeAd) = runCatching {

        currentAd = null

        val nativeView = LayoutInflater.from(parent.context).inflate(layout, parent, false) as NativeAdView
        val mediaView = nativeView.findViewById<MediaView?>(R.id.ad_media)
        mediaView?.mediaContent = nativeAd.mediaContent

        val headlineView = nativeView.findViewById<TextView?>(R.id.ad_headline)
        headlineView?.text = nativeAd.headline

        val bodyView = nativeView.findViewById<TextView?>(R.id.ad_body)
        if (nativeAd.body == null) {
            bodyView?.visibility = View.INVISIBLE
        } else {
            bodyView?.visibility = View.VISIBLE
            bodyView?.text = nativeAd.body
        }

        val callToActionView = nativeView.findViewById<Button?>(R.id.ad_call_to_action)
        if (nativeAd.callToAction == null) {
            callToActionView?.visibility = View.INVISIBLE
        } else {
            callToActionView?.visibility = View.VISIBLE
            callToActionView?.text = nativeAd.callToAction
        }

        val iconView = nativeView.findViewById<ImageView?>(R.id.ad_app_icon)
        if (nativeAd.icon == null) {
            iconView?.visibility = View.GONE
        } else {
            iconView?.setImageDrawable(nativeAd.icon?.drawable)
            iconView?.visibility = View.VISIBLE
        }
        parent.removeAllViews()
        parent.addView(nativeView)
    }

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

}