package com.base.filerecoveryrecyclebin.ads.admob

import android.app.Activity
import android.widget.Toast
import com.base.filerecoveryrecyclebin.BuildConfig
import com.base.filerecoveryrecyclebin.GlobalConfig
import com.base.filerecoveryrecyclebin.ads.AdDisplayUtils
import com.base.filerecoveryrecyclebin.ads.AdmobMaxHelper.lastShowedOnHiddenTime
import com.base.filerecoveryrecyclebin.ads.CountdownDialog.dismissLoadingDialog
import com.base.filerecoveryrecyclebin.ads.CountdownDialog.showLoadingScreen
import com.base.filerecoveryrecyclebin.ads.CountdownDialog.startCountdownAndShowAd
import com.base.filerecoveryrecyclebin.ads.admob.AdmobEvent.clickAd
import com.base.filerecoveryrecyclebin.ads.admob.AdmobEvent.pullAd
import com.base.filerecoveryrecyclebin.ads.admob.AdmobEvent.showAd
import com.base.filerecoveryrecyclebin.help.BaseApplication
import com.base.filerecoveryrecyclebin.utils.EventUtils
import com.base.filerecoveryrecyclebin.utils.LogEx
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import org.json.JSONObject
import java.util.UUID

object AdmobInterstitialUtils {

    private val TAG="AdmobInterstitialUtils"
    private var interAd: InterstitialAd? = null
    private var interLoadTime = Long.MAX_VALUE
    private var adLastDisplayTime: Long = 0
    private val mRequest = AdRequest.Builder().build()

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


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

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

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

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


        if (interAd != null) {
            showLoadingScreen(activity) {
                startCountdownAndShowAd {
                    displayInterstitialAd(activity, onHidden)
                }
            }
        } else {
            showLoadingScreen(activity) {}
            loadInterstitialAd(activity) { loaded ->
                if (loaded) {
                    startCountdownAndShowAd {
                        displayInterstitialAd(activity, onHidden)
                    }
                } else {
                    dismissLoadingDialog()
                    onHidden?.invoke()
                }
            }
        }
    }

    fun loadInterstitialAd(activity: Activity, onLoad: ((flag: Boolean) -> Unit)? = null) {
        if (interAd != null) {
            onLoad?.invoke(true)
            return
        }
        if (!AdDisplayUtils.getInstance().shouldShowAd("InterAd")) {
            onLoad?.invoke(false)
            return
        }
        val reqId = UUID.randomUUID().toString()
        val obj = JSONObject()
        obj.put("req_id", reqId)
        obj.put("ad_type", "interAd")
        obj.put("from", activity.javaClass.simpleName)
        EventUtils.event("ad_pull_start", ext = obj)
        InterstitialAd.load(
            activity, GlobalConfig.ID_ADMOB_INTER,
            mRequest,
            object : InterstitialAdLoadCallback() {
                override fun onAdFailedToLoad(p0: LoadAdError) {
                    interAd = null
                    onLoad?.invoke(false)
                    pullAd(p0.responseInfo, "interAd", p0.message, reqId = reqId)
                    if (BuildConfig.DEBUG) {
                        Toast.makeText(
                            BaseApplication.context,
                            "拉取失败" + p0.message,
                            Toast.LENGTH_SHORT
                        ).show()
                    }

                }

                override fun onAdLoaded(ad: InterstitialAd) {
                    interAd = ad
                    onLoad?.invoke(true)
                    interLoadTime = System.currentTimeMillis()
                    pullAd(ad.responseInfo, "interAd", reqId = reqId)
                    ad.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(ad)
                }
            })
    }


    private fun displayInterstitialAd(activity: Activity, onHidden: (() -> Unit)? = null) {
        val thisInterAd = interAd
        interAd = null
        thisInterAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
            override fun onAdClicked() {
                clickAd(thisInterAd?.responseInfo, "interAd")
                AdDisplayUtils.getInstance().incrementAdClickCount()
            }

            override fun onAdDismissedFullScreenContent() {
                interAd = null
                onHidden?.invoke()
                loadInterstitialAd(activity)
                lastShowedOnHiddenTime = System.currentTimeMillis()
            }

            override fun onAdFailedToShowFullScreenContent(p0: AdError) {
                interAd = null
                onHidden?.invoke()
                loadInterstitialAd(activity)
            }

            override fun onAdShowedFullScreenContent() {
                showAd(thisInterAd?.responseInfo, "interAd", activity)
                AdDisplayUtils.getInstance().incrementAdDisplayCount()
                adLastDisplayTime = System.currentTimeMillis() / 1000
            }
        }
        thisInterAd?.show(activity)
    }
}