package com.base.datarecovery.ads.max

import android.annotation.SuppressLint
import android.app.Activity
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 com.base.datarecovery.ads.AdDisplayUtils
import com.base.datarecovery.ads.AdmobMaxHelper
import com.base.datarecovery.ads.AdmobMaxHelper.isAdInit
import com.base.datarecovery.help.ConfigHelper
import com.base.datarecovery.utils.EventUtils
import com.base.datarecovery.utils.LogEx
import com.base.datarecovery.view.CustomDialog
import org.json.JSONObject
import java.util.UUID
import java.util.concurrent.TimeUnit
import kotlin.math.min
import kotlin.math.pow

object AdMaxInterstitialUtils {

    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 retryAttempt = 0

    @SuppressLint("StaticFieldLeak")
    private var customDialog: CustomDialog? = null

    private var activityString: String = ""

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

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

                    loadingListener?.invoke()
                    loadingListener = null

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

                override fun onAdLoadFailed(p0: String, p1: MaxError) {
                    LogEx.logDebug(TAG, "onAdLoadFailed")
                    val reqId = UUID.randomUUID().toString()
                    AdMaxEvent.pullAd(null, "interAd", reqId = reqId, error = p1.message, code = p1.code)
                    AdDisplayUtils.getInstance().incrementAdRequestFailCount()
                    retryAttempt++
                    LogEx.logDebug(TAG, "onAdLoadFailed retryAttempt=$retryAttempt")
                    if (retryAttempt == 1) {
                        customDialog?.dismiss()
                        onHidden?.invoke()
                        onHidden = null
                        retryAttempt = 0
                    }
                }

                override fun onAdDisplayed(p0: MaxAd) {
                    LogEx.logDebug(TAG, "onAdDisplayed")
                    AdDisplayUtils.getInstance().incrementAdDisplayCount()
                    AdMaxEvent.showAd(p0, "interAd", activityString)
                }

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

                override fun onAdClicked(p0: MaxAd) {
                    LogEx.logDebug(TAG, "onAdClicked activity=$activityString")
                    AdDisplayUtils.getInstance().incrementAdClickCount()
                    AdMaxEvent.clickAd(p0, "interAd")
                }


                override fun onAdDisplayFailed(p0: MaxAd, p1: MaxError) {
                    LogEx.logDebug(TAG, "onAdDisplayFailed")
                    val obj2 = JSONObject()
                    obj2.put("code", p1.code)
                    obj2.put("reason", p1.message)
                    obj2.put("ad_unit", "interAd")
                    EventUtils.event("ad_show_error", ext = obj2)
                }
            })
            interstitialAd?.setRevenueListener(AdMaxEvent.EventOnPaidEventListener())
        }
    }

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

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

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


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

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

        val obj1 = JSONObject()
        obj1.put("ad_unit", "interAd")
        EventUtils.event("ad_prepare_show", ext = obj1)

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

    }

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


    private fun showAdDialogAndLoadInterstitial(
        activity: Activity,
    ) {
        if (!activity.isFinishing && !activity.isDestroyed) {
            customDialog = CustomDialog(activity, R.layout.dialog_ad_loading)
            // 设置对话框的样式和内容
            customDialog?.show()
        }
        loadingListener = {
            customDialog?.dismiss()
            interstitialAd?.showAd(activity)
        }

    }

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

        if (!AdDisplayUtils.getInstance().shouldShowAd("interAd")) {
            return
        }
        if (interstitialAd?.isReady == true) {
            return
        }
        if (isAdInit.get()) {
            LogEx.logDebug(TAG, "loadInterstitialAd")
            val reqId = UUID.randomUUID().toString()
            val obj = JSONObject()
            obj.put("req_id", reqId)
            obj.put("ad_type", "interAd")
            EventUtils.event("ad_pull_start", ext = obj)
            interstitialAd?.loadAd()
        }
    }


}