package com.base.pdfreaderallpdfreader.ads.admob

import android.app.Activity
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.base.pdfreaderallpdfreader.BuildConfig
import com.base.pdfreaderallpdfreader.R
import com.base.pdfreaderallpdfreader.ads.AdDisplayUtils
import com.base.pdfreaderallpdfreader.ads.admob.AdmobEvent.clickAd
import com.base.pdfreaderallpdfreader.ads.admob.AdmobEvent.pullAd
import com.base.pdfreaderallpdfreader.ads.admob.AdmobEvent.showAd
import com.base.pdfreaderallpdfreader.helper.ConfigHelper
import com.base.pdfreaderallpdfreader.helper.EventUtils
import com.base.pdfreaderallpdfreader.helper.MyApplication
import com.base.pdfreaderallpdfreader.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

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

        if (isLoading) {
            return
        }
        isLoading = true
        if (!AdDisplayUtils.shouldShowNative()) {
            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
            it.setOnPaidEventListener(AdmobEvent.EventOnPaidEventListener(it))
            LogEx.logDebug(TAG, "nativeAd=${nativeAd.toString()}")

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

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

            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", ext = obj)
        if (!AdDisplayUtils.shouldShowNative()) {
            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

            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()
            loadingListener = null
        }

    }


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

    fun onDestroy() {
        nativeAd?.destroy()
        nativeAd = null
    }

}