package com.base.datarecovery.ads

import android.app.Activity
import com.base.datarecovery.ads.AdmobCommonUtils.isMultiClick
import com.base.datarecovery.ads.AdmobEvent.clickAd
import com.base.datarecovery.ads.AdmobEvent.pullAd
import com.base.datarecovery.ads.AdmobEvent.showAd
import com.base.datarecovery.help.BaseApplication
import com.base.datarecovery.help.ConfigHelper
import com.base.datarecovery.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.appopen.AppOpenAd
import org.json.JSONObject
import java.util.UUID

object AdmobOpenUtils {

    private val TAG = "AdmobOpenUtils"
    private val mRequest = AdRequest.Builder().build()
    private var openLoadTime = Long.MAX_VALUE
    private var mOpenAd: AppOpenAd? = null
    fun isOpenAdLoaded() = mOpenAd != null

    fun loadAppOpenAd(skip: Boolean = false, onLoad: ((where: Int) -> Unit)? = null) {

        if (mOpenAd != null || skip) {
            onLoad?.invoke(1)
            return
        }
        if (!AdDisplayUtils.getInstance().shouldShowAd()) {
            onLoad?.invoke(2)
            return
        }
        val reqId = UUID.randomUUID().toString()
        val obj = JSONObject()
        obj.put("req_id", reqId)
        obj.put("ad_type", "openAd")
//        EventUtils.event("ad_pull_start", ext = obj)
        AppOpenAd.load(
            BaseApplication.context,
            ConfigHelper.openAdmobId,
            mRequest,
            object : AppOpenAd.AppOpenAdLoadCallback() {
                override fun onAdLoaded(ad: AppOpenAd) {
                    openLoadTime = System.currentTimeMillis()
                    mOpenAd = ad
                    onLoad?.invoke(3)
                    pullAd(ad.responseInfo, "openAd", reqId = reqId)
                    ad.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(ad)
                }

                override fun onAdFailedToLoad(p0: LoadAdError) {
                    LogEx.logDebug(TAG, "LoadAdError ${p0.message}")
                    mOpenAd = null
                    onLoad?.invoke(4)
                    pullAd(p0.responseInfo, "openAd", p0.message, reqId = reqId)
                }
            })
    }

    fun showAppOpenAd(activity: Activity, skip: Boolean = false, onHidden: ((where: Int) -> Unit)? = null) {

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }
        if (!AdDisplayUtils.getInstance().shouldShowAd()) {
            onHidden?.invoke(1)
            return
        }
        val obj = JSONObject()
        obj.put("ad_unit", "openAd")
//        EventUtils.event("ad_prepare_show", ext = obj)
        if (System.currentTimeMillis() - openLoadTime > 1000 * 60 * 60) {
            mOpenAd = null
            loadAppOpenAd()
            onHidden?.invoke(2)
            val obj = JSONObject()
            obj.put("ad_unit", "openAd")
//            EventUtils.event("ad_expire", ext = obj)
            return
        }
        if (mOpenAd != null) {
            val thisMOpenAd = mOpenAd
            mOpenAd = null
            thisMOpenAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdClicked() {
                    clickAd(thisMOpenAd?.responseInfo, "openAd")
                    isMultiClick(thisMOpenAd)
                }

                override fun onAdDismissedFullScreenContent() {
                    mOpenAd = null
                    onHidden?.invoke(3)
                    loadAppOpenAd()
                }

                override fun onAdFailedToShowFullScreenContent(p0: AdError) {
                    mOpenAd = null
                    onHidden?.invoke(4)
                    loadAppOpenAd()
                    val obj = JSONObject()
                    obj.put("reason", p0.message)
                    obj.put("ad_unit", "openAd")
//                    EventUtils.event("ad_show_error", ext = obj)
                }

                override fun onAdShowedFullScreenContent() {
                    showAd(thisMOpenAd?.responseInfo, "openAd", activity)
                }
            }
            thisMOpenAd?.show(activity)
        } else {
            onHidden?.invoke(5)
            loadAppOpenAd()
            val obj = JSONObject()
            obj.put("reason", "no_ad")
            obj.put("ad_unit", "openAd")
//            EventUtils.event("ad_show_error", ext = obj)
        }
    }
}