package com.base.pdfreaderallpdfreader.ads.admob

import android.app.Activity
import com.base.pdfreaderallpdfreader.BuildConfig
import com.base.pdfreaderallpdfreader.ads.AdDisplayUtils
import com.base.pdfreaderallpdfreader.ads.AdmobHelper.lastShowedOnHiddenTime
import com.base.pdfreaderallpdfreader.ads.admob.AdmobEvent.clickAd
import com.base.pdfreaderallpdfreader.ads.admob.AdmobEvent.pullAd
import com.base.pdfreaderallpdfreader.ads.admob.AdmobEvent.showAd
import com.base.pdfreaderallpdfreader.helper.ConfigHelper
import com.base.pdfreaderallpdfreader.helper.EventUtils
import com.base.pdfreaderallpdfreader.helper.MyApplication
import com.base.pdfreaderallpdfreader.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

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

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


    fun loadAppOpenAd(onLoad: ((loaded: Boolean) -> Unit)? = null) {

        if (mOpenAd != null) {
            onLoad?.invoke(true)
            return
        }
        if (!AdDisplayUtils.shouldShowOpenAd()) {
            onLoad?.invoke(false)
            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(true)
                    pullAd(ad.responseInfo, "openAd", reqId = reqId)
                    ad.onPaidEventListener = AdmobEvent.EventOnPaidEventListener(ad)
                    AdDisplayUtils.incrementOpenRequestCount()
                }

                override fun onAdFailedToLoad(p0: LoadAdError) {
                    LogEx.logDebug(TAG, "LoadAdError ${p0.message}")
                    mOpenAd = null
                    onLoad?.invoke(false)
                    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) {
            LogEx.logDebug(TAG, "activity isDestroyed")
            return
        }
        if (!AdDisplayUtils.shouldShowOpenAd()) {
            onHidden?.invoke(false)
            return
        }
        if (isAdExpired()) {
            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")
                    AdDisplayUtils.incrementClickShow()
                }

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

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

                override fun onAdShowedFullScreenContent() {
                    showBefore?.invoke(true)
                    showAd(thisMOpenAd?.responseInfo, "openAd", activity)

                    AdDisplayUtils.incrementOpenShow()
                }
            }
            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)
                }
            }
        }
    }
}