package com.base.locationsharewhite.ads.admob

import android.app.Activity
import android.content.Context
import com.base.locationsharewhite.BuildConfig
import com.base.locationsharewhite.ads.AdsShowCallBack
import com.base.locationsharewhite.ads.BaseAdMgr
import com.base.locationsharewhite.helper.ConfigHelper
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 java.lang.ref.WeakReference

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

    private val adLoadCallback = 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)
            }
        }

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

    override fun loadAd(context: Context) {
        if (!loadingAd && LimitUtils.isAdShow()) {
            loadingAd = true
            //计数
            LimitUtils.addRequestNum()
            AppOpenAd.load(
                context,
                if (BuildConfig.DEBUG) ConfigHelper.openAdmobIdTest else ConfigHelper.openAdmobId,
                AdRequest.Builder().build(),
                adLoadCallback
            )
        }
    }

    override fun show(activity: Activity, showCallBack: AdsShowCallBack?) {
        if (activity.isFinishing || activity.isDestroyed || !LimitUtils.isAdShow()) {
            showCallBack?.failed()
            return
        }
        if (showingAd) {
            // 开屏广告正在展示
            return
        }
        if (showCallBack != null && this.showCallBack != showCallBack) this.showCallBack =
            showCallBack
        if (currentAd == null || !adAvailable()) {
            //缓存广告过期
            currentAd = null
            if (activityRef == null) {
                activityRef = WeakReference(activity)
                // 开屏广告不可用或者缓存超时过期，重新加载
                loadAd(activity.applicationContext)
            } else {
                activityRef = null
                this.showCallBack?.failed()
                this.showCallBack = null
            }
            return
        }
        currentAd?.run {
            fullScreenContentCallback = object : FullScreenContentCallback() {
                override fun onAdShowedFullScreenContent() {
                    super.onAdShowedFullScreenContent()
                    // 广告展示
                    currentAd = null
                    activityRef = null
                    this@AdOpenMgr.showCallBack?.show()

                    //计数
                    LimitUtils.addDisplayNum()
                }

                override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                    super.onAdFailedToShowFullScreenContent(adError)
                    // 广告展示失败，清空缓存数据，重新加载
                    showingAd = false
                    currentAd = null
                    activityRef = null
                    this@AdOpenMgr.showCallBack?.failed()
                    this@AdOpenMgr.showCallBack = null
                }

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

                override fun onAdClicked() {
                    super.onAdClicked()
                    //计数
                    LimitUtils.addClickNum()
                }
            }
            showingAd = true
            show(activity)
        }
    }

    override fun adAvailable(): Boolean {
        return ((System.currentTimeMillis() - lastTime) / 1000 / 60).toInt() < 30
    }
}