package com.base.datarecovery.ads.max

import android.app.Activity
import android.content.Context
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxAppOpenAd
import com.base.datarecovery.ads.AdDisplayUtils
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.ads.admob.AdmobCommonUtils
import com.base.datarecovery.help.ConfigHelper
import com.base.datarecovery.utils.EventUtils
import com.base.datarecovery.utils.LogEx
import org.json.JSONObject

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

    private fun setListener(context: Activity) {
        if (appOpenAd == null) {
            appOpenAd = MaxAppOpenAd(ConfigHelper.openAdMaxId, context)

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

                override fun onAdLoadFailed(p0: String, p1: MaxError) {
                    LogEx.logDebug(TAG, "广告拉取失败了，onAdLoadFailed:" + p1.message.toString())
                    LogEx.logDebug(TAG, "广告拉取失败了，onAdLoadFailed:" + p0)
                    LogEx.logDebug(TAG, "广告拉取失败了，onAdLoadFailed:" + p1.code)
                    onHidden?.invoke()
                    AdDisplayUtils.getInstance().incrementAdRequestFailCount()
                    AdMaxEvent.pullAd(null, "openAd")
                }


                override fun onAdDisplayed(p0: MaxAd) {
                    AdDisplayUtils.getInstance().incrementAdDisplayCount()
                    AdMaxEvent.showAd(p0, "openAd", Activity())
                }

                override fun onAdHidden(p0: MaxAd) {
                    onHidden?.invoke()
                    loadAppOpenAd(context)
                    loadingListener = null
                }

                override fun onAdClicked(p0: MaxAd) {
                    AdDisplayUtils.getInstance().incrementAdClickCount()
//                    com.base.datarecovery.ads.max.AdMaxEvent.clickAd(appOpenAd, "openAd")
                    AdmobCommonUtils.isMultiClick(appOpenAd)
                    AdMaxEvent.clickAd(p0, "openAd")
                }


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

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

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

        setListener(activity)

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

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

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

        if (!AdmobMaxHelper.isAdInit.get()) {
            onHidden?.invoke()
            return
        }


        LogEx.logDebug(TAG, "showAppOpenAd")
        val obj1 = JSONObject()
        obj1.put("ad_unit", "openAd")
        EventUtils.event("ad_prepare_show", ext = obj1)
        AdMaxOpenUtils.onHidden = onHidden

        if (appOpenAd?.isReady == true) {
            LogEx.logDebug(TAG, "广告准备好了，展示广告")
            appOpenAd?.showAd()
        } else {
            LogEx.logDebug(TAG, "展示时候，发现广告需要拉取")
            appOpenAd?.loadAd()
            loadingListener = {
                LogEx.logDebug(TAG, "loadingListener callback")
                loaded?.invoke()
                appOpenAd?.showAd()
                loadingListener = null
            }
        }
    }

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

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

            return
        }

        if (AdmobMaxHelper.isAdInit.get()) {
            LogEx.logDebug(TAG, "loadAppOpenAd2")
            appOpenAd?.loadAd()
        } else {
            LogEx.logDebug(TAG, "loadAppOpenAd3")
        }
    }

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

}

