package com.base.pdfviewerscannerwhite.ads.admob

import android.app.Activity
import android.app.Dialog
import android.widget.Toast
import com.base.pdfviewerscannerwhite.BuildConfig
import com.base.pdfviewerscannerwhite.ads.AdDialog.showAdPreparingDialog
import com.base.pdfviewerscannerwhite.ads.AdDisplayUtils
import com.base.pdfviewerscannerwhite.ads.admob.AdmobEvent.clickAd
import com.base.pdfviewerscannerwhite.ads.admob.AdmobEvent.pullAd
import com.base.pdfviewerscannerwhite.ads.admob.AdmobEvent.showAd
import com.base.pdfviewerscannerwhite.ads.AdmobHelper.lastShowedOnHiddenTime
import com.base.pdfviewerscannerwhite.helper.ConfigHelper
import com.base.pdfviewerscannerwhite.helper.EventUtils
import com.base.pdfviewerscannerwhite.helper.MyApplication
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 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,
        isReLoadAd: Boolean = false,
        isShowDialog: Boolean = true,
        onHidden: ((showed: Boolean) -> Unit)? = null
    ) {

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

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

        if (!AdDisplayUtils.shouldShowInterAd()) {
            onHidden?.invoke(false)
            return
        }

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

        if (interAd != null) {
            var dialog: Dialog? = null
            if (!activity.isFinishing && !activity.isDestroyed) {
                dialog = activity.showAdPreparingDialog()
            }
            displayInterstitialAd(activity, dialog, onHidden)
        } else {
            showAdDialogAndLoadInterstitial(activity, isReLoadAd, isShowDialog, onHidden)
        }
    }

    fun loadInterstitialAd(activity: Activity, onLoad: (() -> Unit)? = null) {
        if (interAd != null) {
            onLoad?.invoke()
            return
        }
        if (!AdDisplayUtils.shouldShowInterAd()) {
            onLoad?.invoke()
            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,
            if (BuildConfig.DEBUG) ConfigHelper.interAdmobIdTest else ConfigHelper.interAdmobId,
            mRequest,
            object : InterstitialAdLoadCallback() {
                override fun onAdFailedToLoad(p0: LoadAdError) {
                    interAd = null
                    onLoad?.invoke()
                    pullAd(p0.responseInfo, "interAd", p0.message, reqId = reqId)
                    if (BuildConfig.DEBUG) {
                        Toast.makeText(
                            MyApplication.context, "拉取失败" + p0.message, Toast.LENGTH_SHORT
                        ).show()
                    }
                }

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

    private fun showAdDialogAndLoadInterstitial(
        activity: Activity,
        isReLoadAd: Boolean,
        isShowDialog: Boolean,
        onHidden: ((showed: Boolean) -> Unit)?
    ) {
        if (!isShowDialog) {
            onHidden?.invoke(false)
            return
        }
        var mDialog: Dialog? = null
        if (!activity.isFinishing && !activity.isDestroyed) {
            mDialog = activity.showAdPreparingDialog()
            mDialog.show()
        }


        loadInterstitialAd(activity) {
            mDialog?.dismiss()
            if (!isReLoadAd) {
                showInterstitialAd(activity, true, false) {
                    onHidden?.invoke(it)
                }
            }
        }
        if (isReLoadAd) {
            mDialog?.dismiss()
            onHidden?.invoke(false)
        }
    }

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

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

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

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

    fun haveReadAd(): Boolean {
        return interAd != null
    }
}