package com.base.locationsharewhite.ads.admob

import android.app.Activity
import android.content.Context
import com.base.locationsharewhite.ads.AdsShowCallBack
import com.base.locationsharewhite.ads.AdsType
import com.base.locationsharewhite.ads.BaseAdMgr
import com.base.locationsharewhite.helper.EventUtils
import com.base.locationsharewhite.helper.config.ConstConfig
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.lang.ref.WeakReference
import java.util.UUID

/**
 * 开屏广告加载显示管理类
 */
class AdOpenMgr : BaseAdMgr<AppOpenAd>() {

    private var lastOpenDate: Long = 0

    override fun loadAd(context: Context) {
        if (!loadingAd && LimitUtils.isAdShow(AdsType.OPEN)) {
            loadingAd = true
            //计数
            LimitUtils.addRequestNum()
            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(
                context,
                ConstConfig.openAdId,
                AdRequest.Builder().build(),
                object : AppOpenAd.AppOpenAdLoadCallback() {
                    override fun onAdLoaded(appOpenAd: AppOpenAd) {
                        super.onAdLoaded(appOpenAd)
                        // 开屏广告加载成功
                        currentAd = appOpenAd
                        loadingAd = false
                        lastTime = System.currentTimeMillis()
                        val ac = activityRef?.get()
                        if (ac != null) {
                            show(ac)
                        }
                        AdmobEvent.pullAd(appOpenAd.responseInfo, "openAd", reqId = reqId)
                        appOpenAd.onPaidEventListener =
                            AdmobEvent.EventOnPaidEventListener(appOpenAd)
                    }

                    override fun onAdFailedToLoad(loadAdError: LoadAdError) {
                        super.onAdFailedToLoad(loadAdError)
                        // 开屏广告加载失败
                        // 官方不建议在此回调中重新加载广告
                        // 如果确实需要，则必须限制最大重试次数，避免在网络受限的情况下连续多次请求
                        loadingAd = false
                        if (activityRef != null && !showingAd && showCallBack != null) {
                            showCallBack?.googleFailed()
                            showCallBack = null
                        }
                        AdmobEvent.pullAd(
                            loadAdError.responseInfo,
                            "openAd",
                            loadAdError.message,
                            reqId = reqId
                        )
                    }
                }
            )
        }
    }

    override fun show(activity: Activity, showCallBack: AdsShowCallBack?) {
        if (activity.isFinishing || activity.isDestroyed) {
            showCallBack?.failed()
            return
        }

        if (!LimitUtils.isAdShow(AdsType.OPEN)) {
            showCallBack?.failed()
            return
        }
        if (LimitUtils.isIntervalLimited(lastOpenDate)) {
            showCallBack?.failed()
            return
        }

        if (showingAd) {
            // 开屏广告正在展示
            return
        }
        if (showCallBack != null && this.showCallBack != showCallBack) this.showCallBack =
            showCallBack
        if ((currentAd == null).also {
                if (it) {
                    val obj = JSONObject()
                    obj.put("reason", "no_ad")
                    obj.put("ad_unit", "openAd")
                    EventUtils.event("ad_show_error", ext = obj)
                }
            } || (!adAvailable()).also {
                if (it) {
                    val obj2 = JSONObject()
                    obj2.put("ad_unit", "openAd")
                    EventUtils.event("ad_expire", ext = obj2)
                }
            }) {
            //缓存广告过期
            currentAd = null
            if (activityRef == null) {
                activityRef = WeakReference(activity)
                // 开屏广告不可用或者缓存超时过期，重新加载
                loadAd(activity.applicationContext)
            } else {
                activityRef = null
                this.showCallBack?.failed()
                this.showCallBack = null
                val obj = JSONObject()
                obj.put("reason", "no_ad")
                obj.put("ad_unit", "openAd")
                EventUtils.event("ad_show_error", ext = obj)
            }
            return
        }
        val obj1 = JSONObject()
        obj1.put("ad_unit", "openAd")
        EventUtils.event("ad_prepare_show", ext = obj1)
        currentAd?.run {
            fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {
                    super.onAdShowedFullScreenContent()
                    lastOpenDate = System.currentTimeMillis()
                    // 广告展示
                    currentAd = null
                    activityRef = null
                    this@AdOpenMgr.showCallBack?.show()
                    //计数
                    LimitUtils.addDisplayNum()
                    AdmobEvent.showAd(this@run.responseInfo, "openAd", activity)
                }

                override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                    super.onAdFailedToShowFullScreenContent(adError)
                    // 广告展示失败，清空缓存数据，重新加载
                    showingAd = false
                    currentAd = null
                    activityRef = null
                    this@AdOpenMgr.showCallBack?.googleFailed()
                    this@AdOpenMgr.showCallBack = null
                    val obj = JSONObject()
                    obj.put("reason", adError.message)
                    obj.put("code", adError.code)
                    obj.put("ad_unit", "openAd")
                    EventUtils.event("ad_show_error", ext = obj)
                }

                override fun onAdDismissedFullScreenContent() {
                    super.onAdDismissedFullScreenContent()
                    // 广告关闭，清空缓存数据，重新加载
                    showingAd = false
                    this@AdOpenMgr.showCallBack?.close()
                    this@AdOpenMgr.showCallBack = null
                    loadAd(activity.applicationContext)
                }

                override fun onAdClicked() {
                    super.onAdClicked()
                    AdmobEvent.clickAd(this@run.responseInfo, "openAd")
                    //计数
                    LimitUtils.addClickNum()
                }
            }
            showingAd = true
            show(activity)
        }
    }

    override fun adAvailable() = ((System.currentTimeMillis() - lastTime) / 1000 / 60).toInt() < 30
}