package com.base.browserwhite.ads.admob

import android.app.Activity
import com.base.browserwhite.BuildConfig
import com.base.browserwhite.MyApplication
import com.base.browserwhite.ads.AdDisplayUtils
import com.base.browserwhite.ads.admob.AdmobEvent.clickAd
import com.base.browserwhite.ads.admob.AdmobEvent.pullAd
import com.base.browserwhite.ads.admob.AdmobEvent.showAd
import com.base.browserwhite.help.ConfigHelper
import com.base.browserwhite.help.EventUtils
import com.base.browserwhite.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 const 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("openAd")) {
            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(
            MyApplication.context,
            if (BuildConfig.DEBUG) ConfigHelper.openAdmobIdTest else ConfigHelper.openAdmobId,
            mRequest,
            object : AppOpenAd.AppOpenAdLoadCallback() {
                override fun onAdLoaded(ad: AppOpenAd) {
                    LogEx.logDebug(TAG, "onAdLoaded")
                    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,
        isRetry: Boolean = false,
        showBefore: ((flag: Boolean) -> Unit)? = null,
        onHidden: ((showed: Boolean) -> Unit)? = null
    ) {

        if (activity.isFinishing || activity.isDestroyed) {
            return
        }
        if (!AdDisplayUtils.getInstance().shouldShowAd("openAd")) {
            onHidden?.invoke(false)
            return
        }
        if (System.currentTimeMillis() - openLoadTime > 1000 * 60 * 60) {
            LogEx.logDebug(TAG, "openLoadTime out time")
            mOpenAd = null
            loadAppOpenAd()
            onHidden?.invoke(false)
            val obj2 = JSONObject()
            obj2.put("ad_unit", "openAd")
            EventUtils.event("ad_expire", ext = obj2)
            return
        }
        if (!isRetry) {
            val obj1 = JSONObject()
            obj1.put("ad_unit", "openAd")
            EventUtils.event("ad_prepare_show", ext = obj1)
            LogEx.logDebug(TAG, "open ad_prepare_show")
        }

        if (mOpenAd != null) {
            LogEx.logDebug(TAG, "mOpenAd!=null")
            val thisMOpenAd = mOpenAd
            mOpenAd = null
            thisMOpenAd?.fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdClicked() {
                    clickAd(thisMOpenAd?.responseInfo, "openAd")
                }

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

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

                override fun onAdShowedFullScreenContent() {
                    showBefore?.invoke(true)
                    showAd(thisMOpenAd?.responseInfo, "openAd", activity)
                }
            }
            thisMOpenAd?.show(activity)
        } else {
            LogEx.logDebug(TAG, "mOpenAd=null")
            loadAppOpenAd {
                if (mOpenAd != null) {
                    showAppOpenAd(activity, true, showBefore, onHidden)
                } else {
                    val obj = JSONObject()
                    obj.put("reason", "no_ad")
                    obj.put("ad_unit", "openAd")
                    EventUtils.event("ad_show_error", ext = obj)
                    onHidden?.invoke(false)
                }
            }
        }
    }
}