package rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.cherryedto.ranchedto.gunedto

import android.app.Activity
import android.app.Dialog
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxInterstitialAd
import com.base.datarecovery.R
import org.json.JSONObject
import rowedto.jockeyedto.sheetedto.Epicalyxedto.Companion.isInterOpenShowing
import rowedto.jockeyedto.sheetedto.balsamedto.formaledto.orientationedto.Standardedto
import rowedto.jockeyedto.sheetedto.knewedto.economicedto.copyrightedto.Celledto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Dishedto
import rowedto.jockeyedto.sheetedto.raceedto.pavementedto.Slantedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Modestedto
import rowedto.jockeyedto.sheetedto.strangeedto.pyramidedto.particlesedto.Scandaledto.lastShowedOnHiddenTime
import java.util.UUID

object Jovialedto {

    private val TAG = "AdMaxInterstitialUtils"
    private var interstitialAd: MaxInterstitialAd? = null
    private var interLoadTime = Long.MAX_VALUE
    private var onHidden: (() -> Unit)? = null
    private var loadingListener: (() -> Unit)? = null
    private var activityString: String = ""

    private fun setListener(activity: Activity) {
        activityString = activity::class.java.toString().split(".").last()
        if (interstitialAd == null) {

            interstitialAd = MaxInterstitialAd(Celledto.interAdMaxId, activity)
            interstitialAd?.setListener(object : MaxAdListener {
                override fun onAdLoaded(p0: MaxAd) {
                    Dishedto.logDebug(TAG, "onAdLoaded")

                    loadingListener?.invoke()
                    loadingListener = null

                    interLoadTime = System.currentTimeMillis()
                    val reqId = UUID.randomUUID().toString()
                    Refereeedto.pullAd(p0, "interAd", reqId = reqId)
                }

                override fun onAdLoadFailed(p0: String, p1: MaxError) {
                    Dishedto.logDebug(TAG, "广告拉取失败了，onAdLoadFailed:" + p0)
                    Dishedto.logDebug(TAG, "广告拉取失败了，onAdLoadFailed:" + p1.message.toString())
                    Dishedto.logDebug(TAG, "广告拉取失败了，onAdLoadFailed:" + p1.code)
                    val reqId = UUID.randomUUID().toString()
                    Refereeedto.pullAd(null, "interAd", reqId = reqId, error = p1.message, code = p1.code)
                    Modestedto.getInstance().incrementAdRequestFailCount()

                    loadingListener?.invoke()
                    loadingListener = null
                }

                override fun onAdDisplayed(p0: MaxAd) {
                    Dishedto.logDebug(TAG, "onAdDisplayed")
                    Modestedto.getInstance().incrementAdDisplayCount()
                    Refereeedto.showAd(p0, "interAd", activityString)

                    isInterOpenShowing = true
                }

                override fun onAdHidden(p0: MaxAd) {
                    Dishedto.logDebug(TAG, "onAdHidden")
                    onHidden?.invoke()
                    onHidden = null
                    Causeedto.loadAppOpenAd(activity)
//                    loadInterstitialAd(activity)

                    isInterOpenShowing = false
                    lastShowedOnHiddenTime = System.currentTimeMillis()
                }

                override fun onAdClicked(p0: MaxAd) {
                    Dishedto.logDebug(TAG, "onAdClicked activity=$activityString")
                    Modestedto.getInstance().incrementAdClickCount()
                    Refereeedto.clickAd(p0, "interAd")
                }


                override fun onAdDisplayFailed(p0: MaxAd, p1: MaxError) {
                    Dishedto.logDebug(TAG, "onAdDisplayFailed")
                    onHidden?.invoke()
                    onHidden = null
                    val obj2 = JSONObject()
                    obj2.put("code", p1.code)
                    obj2.put("reason", p1.message)
                    obj2.put("ad_unit", "interAd")
                    Slantedto.event("ad_show_error", ext = obj2)

                    isInterOpenShowing = false
                }
            })
            interstitialAd?.setRevenueListener(Refereeedto.EventOnPaidEventListener())
        }
    }

    fun showInterstitialAd(activity: Activity, onHidden: (() -> Unit)? = null) {
        setListener(activity)

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }

        if (!Modestedto.getInstance().shouldShowAd("interAd")) {
            onHidden?.invoke()
            return
        }

        if (isAdExpired()) {
            val obj2 = JSONObject()
            obj2.put("ad_unit", "interAd")
            Slantedto.event("ad_expire", ext = obj2)
            loadInterstitialAd(activity)
            onHidden?.invoke()
            return
        }


        Dishedto.logDebug(TAG, "showInterstitialAd,展示插屏广告")

        val obj1 = JSONObject()
        obj1.put("ad_unit", "interAd")
        Slantedto.event("ad_prepare_show", ext = obj1)
        isInterOpenShowing = false

        if (interstitialAd?.isReady == true) {
            Dishedto.logDebug(TAG, "有缓存直接播放。")
            this.onHidden = onHidden
            interstitialAd?.showAd(activity)
        } else {
            Dishedto.logDebug(TAG, "展示广告时，没有缓存，需要拉取。")
            val obj2 = JSONObject()
            obj2.put("reason", "no cache ad")
            obj2.put("ad_unit", "interAd")
            Slantedto.event("ad_nocache_pull", ext = obj2)
            val loaded = loadInterstitialAd(activity)
            if (loaded) {
                Dishedto.logDebug(TAG, "loaded=true")
                val dialog = showAdDialogAndLoadInterstitial(activity)
                loadingListener = {
                    dialog?.dismiss()
                    if (interstitialAd?.isReady == true) {
                        this.onHidden = onHidden
                        interstitialAd?.showAd(activity)
                    } else {
                        onHidden?.invoke()
                    }
                }
            } else {
                Dishedto.logDebug(TAG, "loaded=false")
                onHidden?.invoke()
            }
        }

    }

    private fun isAdExpired(): Boolean {
        return System.currentTimeMillis() - interLoadTime > 1000 * 60 * 60
    }


    private fun showAdDialogAndLoadInterstitial(
        activity: Activity,
    ): Dialog? {
        var customDialog: Dialog? = null
        if (!activity.isFinishing && !activity.isDestroyed) {
            customDialog = Standardedto(activity, R.layout.saladedto)
            // 设置对话框的样式和内容
            customDialog.show()
        }
        return customDialog
    }

    fun loadInterstitialAd(activity: Activity): Boolean {
        setListener(activity)

        if (!Modestedto.getInstance().shouldShowAd("interAd")) {
            return false
        }
        if (interstitialAd?.isReady == true) {
            return false
        }
//        if (isAdInit.get()) {
            Dishedto.logDebug(TAG, "loadInterstitialAd")
            val reqId = UUID.randomUUID().toString()
            val obj = JSONObject()
            obj.put("req_id", reqId)
            obj.put("ad_type", "interAd")
            Slantedto.event("ad_pull_start", ext = obj)
            interstitialAd?.loadAd()
            Modestedto.getInstance().incrementAdRequestCount()
            return true
//        } else {
//            Dishedto.logDebug(TAG, "isAdInit=$isAdInit")
//            Slantedto.event("isAdInit", value = "loadInterstitialAd isAdInit=${isAdInit.get()}")
//        }
//        return false
    }


}