package com.base.browserwhite.ads.admob

import android.app.Activity
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.base.browserwhite.BuildConfig
import com.base.browserwhite.MyApplication
import com.base.browserwhite.R
import com.base.browserwhite.ads.AdDisplayUtils
import com.base.browserwhite.ads.admob.AdmobEvent.clickAd
import com.base.browserwhite.ads.admob.AdmobEvent.pullAd
import com.base.browserwhite.ads.admob.AdmobEvent.showAd
import com.base.browserwhite.help.ConfigHelper
import com.base.browserwhite.help.EventUtils
import com.base.browserwhite.utils.LogEx
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 org.json.JSONObject
import java.util.UUID

object AdmobNativeUtils {

    private const val TAG = "AdmobNativeUtils"
    private var nativeAd: NativeAd? = null
    private var isLoading = false
    private var nativeLoadTime = Long.MAX_VALUE
    private var loadingListener: (() -> Unit)? = null
    private val mRequest = AdRequest.Builder().build()
    var onAdLoaded: (() -> Unit)? = null

    private fun loadNativeAd() {
        if (nativeAd != null) {
            return
        }

        if (isLoading) {
            return
        }
        isLoading = true
        if (!AdDisplayUtils.getInstance().shouldShowAd("NativeAd")) {
            return
        }

        val reqId = UUID.randomUUID().toString()
        val obj = JSONObject()
        obj.put("req_id", reqId)
        obj.put("ad_type", "nativeAd")

        val adLoader = AdLoader.Builder(
            MyApplication.context,
            if (BuildConfig.DEBUG) ConfigHelper.nativeAdmobIdTest else ConfigHelper.nativeAdmobId
        ).forNativeAd {
            nativeLoadTime = System.currentTimeMillis()
            nativeAd = it
            LogEx.logDebug(TAG, "nativeAd=${nativeAd.toString()}")

            isLoading = false
            loadingListener?.invoke()
            pullAd(it.responseInfo, "nativeAd", reqId = reqId)
            it.setOnPaidEventListener(AdmobEvent.EventOnPaidEventListener(it))
        }.withAdListener(object : AdListener() {
            override fun onAdLoaded() {
                super.onAdLoaded()
                onAdLoaded?.invoke()
                onAdLoaded = null
            }

            override fun onAdClicked() {
                clickAd(nativeAd?.responseInfo, "nativeAd")
            }

            override fun onAdFailedToLoad(p0: LoadAdError) {
                LogEx.logDebug(TAG, "onAdFailedToLoad=${p0.message}")
                nativeAd = null
                isLoading = false
                pullAd(p0.responseInfo, "nativeAd", p0.message, reqId = reqId)
                //   Log.e("MXL", "NativeAdFailedToLoad: " + p0.message)
            }
        }).build()
        adLoader.loadAd(mRequest)
    }


    fun showNativeAd(activity: Activity?, parent: ViewGroup, layout: Int = R.layout.layout_admob_native_custom) {
        val obj = JSONObject()
        obj.put("ad_unit", "NativeAd")
        EventUtils.event("ad_prepare_show_native", ext = obj)
        if (!AdDisplayUtils.getInstance().shouldShowAd("NativeAd")) {
            return
        }
        loadingListener = {
            if (System.currentTimeMillis() - nativeLoadTime <= 1000 * 60 * 60) {
                nativeAd?.let {
                    NativeView(parent.context, layout).run {
                        parent.removeAllViews()
                        setNativeAd(it)
                        parent.addView(this)
                        parent.isVisible = true
                        showAd(nativeAd?.responseInfo, "nativeAd", activity)
                    }
                }
            }
            nativeAd = null
            loadingListener = null
            loadNativeAd()
        }
        if (nativeAd == null) {
            loadNativeAd()
            val obj2 = JSONObject()
            obj2.put("reason", "no_ad")
            obj2.put("ad_unit", "nativeAd")
            EventUtils.event("ad_show_error", ext = obj2)
        } else {
            loadingListener?.invoke()
        }

    }


    fun showReadyNativeAd(
        activity: Activity?,
        readyNativeAd: NativeAd?,
        parent: ViewGroup,
        layout: Int = R.layout.layout_admob_native_news
    ) {
        readyNativeAd?.let {
            NativeView(parent.context, layout).run {
                parent.removeAllViews()
                setNativeAd(it)
                parent.addView(this)
                parent.isVisible = true
                showAd(nativeAd?.responseInfo, "nativeAd", activity)
            }
        }
    }

     var readyNative = arrayListOf<NativeAd>()
    fun loadNativeList(count: Int) {
        readyNative.clear()
        repeat(count) {
            val adLoader = AdLoader.Builder(
                MyApplication.context,
                if (BuildConfig.DEBUG) ConfigHelper.nativeAdmobIdTest else ConfigHelper.nativeAdmobId
            ).forNativeAd {
                readyNative.add(it)
            }.withAdListener(object : AdListener() {
                override fun onAdLoaded() {
                    super.onAdLoaded()
                    LogEx.logDebug(TAG, "loadNativeList onAdLoaded")
                }

                override fun onAdClicked() {
                }

                override fun onAdFailedToLoad(p0: LoadAdError) {
                    LogEx.logDebug(TAG, "loadNativeList onAdFailedToLoad")
                }
            }).build()
            adLoader.loadAd(mRequest)
        }
    }
}