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

import android.app.Activity
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxAppOpenAd
import org.json.JSONObject
import rowedto.jockeyedto.sheetedto.Epicalyxedto.Companion.isInterOpenShowing
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 java.util.UUID

object Causeedto {
    private val TAG = "AdMaxOpenUtils"
    private var appOpenAd: MaxAppOpenAd? = null
    private var openLoadTime = Long.MAX_VALUE
    private var onHidden: (() -> Unit)? = null
    private var loadingListener: ((flag: Boolean) -> Unit)? = null
    private var activityString = ""

    private fun setListener(activity: Activity) {
        activityString = activity::class.java.toString().split(".").last()
        if (appOpenAd == null) {
            appOpenAd = MaxAppOpenAd(Celledto.openAdMaxId, activity)

            appOpenAd?.setListener(object : MaxAdListener {
                override fun onAdLoaded(p0: MaxAd) {
                    Dishedto.logDebug(TAG, "广告拉取成功")
                    openLoadTime = System.currentTimeMillis()
                    loadingListener?.invoke(true)
                    loadingListener = null
                    Refereeedto.pullAd(p0, "openAd")
                }

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

                override fun onAdDisplayed(p0: MaxAd) {
                    Modestedto.getInstance().incrementAdDisplayCount()
                    Refereeedto.showAd(p0, "openAd", activityString)

                    isInterOpenShowing = true
                }

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

                    isInterOpenShowing = false
                }

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

                    isInterOpenShowing = false
                }

                override fun onAdClicked(p0: MaxAd) {
                    Modestedto.getInstance().incrementAdClickCount()
                    Refereeedto.clickAd(p0, "openAd")
                }

            })

            appOpenAd?.setRevenueListener(Refereeedto.EventOnPaidEventListener())
        }
    }

    fun showAppOpenAd(
        activity: Activity,
        loadCallBack: ((flag: Boolean) -> Unit)? = null,
        onHidden: (() -> Unit)? = null
    ) {

        setListener(activity)

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

        if (!Modestedto.getInstance().shouldShowAd("openAd")) {
            Dishedto.logDebug(TAG, "!shouldShowAd")
            onHidden?.invoke()
            return
        }

        if (System.currentTimeMillis() - openLoadTime > 1000 * 60 * 60) {
            Dishedto.logDebug(TAG, "openLoadTime > ")
            onHidden?.invoke()
            val obj2 = JSONObject()
            obj2.put("ad_unit", "openAd")
            Slantedto.event("ad_expire", ext = obj2)
            appOpenAd?.loadAd()
        }

//        if (!isAdInit.get()) {
//            Slantedto.event("isAdInit", value = "showAppOpenAd isAdInit=${isAdInit.get()}")
//            onHidden?.invoke()
//            return
//        }


        Dishedto.logDebug(TAG, "showAppOpenAd")
        val obj1 = JSONObject()
        obj1.put("ad_unit", "openAd")
        Slantedto.event("ad_prepare_show", ext = obj1)


        if (appOpenAd?.isReady == true) {
            Dishedto.logDebug(TAG, "广告准备好了，展示广告")
            Causeedto.onHidden = onHidden
            appOpenAd?.showAd()
        } else {
            val obj = JSONObject()
            obj.put("reason", "no cache ad")
            obj.put("ad_unit", "openAd")
            Slantedto.event("ad_nocache_pull", ext = obj)
            Dishedto.logDebug(TAG, "展示时候，发现广告需要拉取")
            val loaded = loadAppOpenAd(activity)
            if (loaded) {
                loadingListener = { loadResult ->
                    loadCallBack?.invoke(loadResult)
                    Dishedto.logDebug(TAG, "loadingListener callback")
                    if (appOpenAd?.isReady == true) {
                        Causeedto.onHidden = onHidden
                        appOpenAd?.showAd()
                    } else {
                        onHidden?.invoke()
                    }
                }
            } else {
                onHidden?.invoke()
            }

        }
    }

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

        if (!Modestedto.getInstance().shouldShowAd("openAd")) {
            Dishedto.logDebug(TAG, "!shouldShowAd")
            return false
        }
        if (appOpenAd?.isReady == true) {
            Dishedto.logDebug(TAG, "appOpenAd?.isReady == true")
            return false
        }

//        if (isAdInit.get()) {
//            Slantedto.event("isAdInit", value = "loadAppOpenAd isAdInit=${isAdInit.get()}")
            Dishedto.logDebug(TAG, "appOpenAd loadAd")
            val reqId = UUID.randomUUID().toString()
            val obj = JSONObject()
            obj.put("req_id", reqId)
            obj.put("ad_type", "openAd")
            Slantedto.event("ad_pull_start", ext = obj)
            appOpenAd?.loadAd()
            Modestedto.getInstance().incrementAdRequestCount()
            return true
//        }
//        return false
    }

    fun isOpenAdLoaded(): Boolean {
        return appOpenAd?.isReady == true
    }

}

