package com.base.datarecovery.ads

import android.app.Activity
import android.view.ViewGroup
import androidx.core.view.isVisible
import com.base.datarecovery.R
import com.base.datarecovery.ads.AdmobCommonUtils.isMultiClick
import com.base.datarecovery.ads.AdmobEvent.clickAd
import com.base.datarecovery.ads.AdmobEvent.pullAd
import com.base.datarecovery.ads.AdmobEvent.showAd
import com.base.datarecovery.help.BaseApplication
import com.base.datarecovery.help.ConfigHelper
import com.base.datarecovery.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 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()

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

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

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

        val adLoader = AdLoader.Builder(
            BaseApplication.context, 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 onAdClicked() {
                clickAd(nativeAd?.responseInfo, "nativeAd")
                isMultiClick(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_native_custom) {
        val obj = JSONObject()
        obj.put("ad_unit", "NativeAd")
//        EventUtils.event("ad_prepare_show", ext = obj)
        if (!AdDisplayUtils.getInstance().shouldShowAd()) {
            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()
        }
    }
}