package com.base.filerecoveryrecyclebin.ads.max

import android.app.Activity
import android.os.Handler
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxInterstitialAd
import com.base.filerecoveryrecyclebin.ads.AdDisplayUtils
import com.base.filerecoveryrecyclebin.help.ConfigHelper
import com.base.filerecoveryrecyclebin.utils.EventUtils
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import org.json.JSONObject
import java.util.concurrent.TimeUnit
import kotlin.math.min
import kotlin.math.pow

object 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

    fun setListener(activity: Activity) {
        if (interstitialAd == null) {
            interstitialAd = MaxInterstitialAd(ConfigHelper.interAdMaxId, activity)
        }

        interstitialAd?.setListener(object : MaxAdListener {
            override fun onAdLoaded(p0: MaxAd) {
                loadingListener?.invoke()
                interLoadTime = System.currentTimeMillis()
                retryAttempt = 0
            }

            override fun onAdDisplayed(p0: MaxAd) {
            }

            override fun onAdHidden(p0: MaxAd) {
                onHidden?.invoke()
            }

            override fun onAdClicked(p0: MaxAd) {
            }

            override fun onAdLoadFailed(p0: String, p1: MaxError) {
                retryAttempt++
                val delayMillis = TimeUnit.SECONDS.toMillis(2.0.pow(min(6, retryAttempt)).toLong())

                MainScope().launch {
                    delay(delayMillis)
                    interstitialAd?.loadAd()
                }
            }

            override fun onAdDisplayFailed(p0: MaxAd, p1: MaxError) {
            }
        })
    }

    fun showInterstitialAd(
        activity: Activity,
        isReLoadAd: Boolean = false,
        isShowDialog: Boolean = true,
        onHidden: (() -> Unit)? = null
    ) {
        setListener(activity)

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }
        val obj1 = JSONObject()
        obj1.put("ad_unit", "interAd")
        EventUtils.event("ad_prepare_show", ext = obj1)

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


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

        this.onHidden = onHidden
        if (interstitialAd?.isReady == true) {
            interstitialAd?.showAd()
        } else {
            interstitialAd?.loadAd()
            loadingListener = {
                interstitialAd?.showAd()
                loadingListener = null
            }
        }

    }

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