package com.all.pdfreader.pdf.reader.ad

import android.app.Activity
import android.util.Log
import com.all.pdfreader.pdf.reader.util.AnalyticsUtils
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.FullScreenContentCallback

class AdInstShower(
    private val activity: Activity,
    private val placement: AdsInsUtil.AdPlacement,
    private val showListener: ShowListener?
) {

    companion object {
        private const val SHOW_INTERVAL = 60_000L // 60秒间隔
        private var lastShowTimestamp = 0L
    }

    init {
        showAd()
    }

    private fun showAd() {
        // ======= 新增：全局展示间隔限制 启动页不处理 =======
        if(placement != AdsInsUtil.AdPlacement.SPL_AND_INTO_HOME){
            val now = System.currentTimeMillis()
            if (now - lastShowTimestamp < SHOW_INTERVAL) {
                val errorMsg = "广告展示过于频繁, 请等待 ${(SHOW_INTERVAL - (now - lastShowTimestamp)) / 1000}s（间隔限制60s）"
                showListener?.onAdShowFailed(errorMsg)
                Log.d(AdsInsUtil.Placement.TAG, "showAd->$errorMsg")
                return
            }
        }

        val interstitialAd = InstAdCacheManager.instance.getAdCache(placement)
            ?: run {
                val errorMsg = "插页式广告缓存为空 = $placement"
                showListener?.onAdShowFailed(errorMsg)
                Log.d(AdsInsUtil.Placement.TAG, "showAd->$errorMsg")
                return
            }

        interstitialAd.fullScreenContentCallback = object : FullScreenContentCallback() {

            override fun onAdShowedFullScreenContent() {
                // ======= 新增：展示成功 记录时间 =======
                lastShowTimestamp = System.currentTimeMillis()
                Log.d(AdsInsUtil.Placement.TAG, "广告 $placement 展示成功")
                AnalyticsUtils.logAdEvent(placement, AnalyticsUtils.AdEvent.SHOW_SUC)
                showListener?.onAdShown()
            }

            override fun onAdDismissedFullScreenContent() {
                // 用户关闭广告
                InstAdCacheManager.instance.remove(placement)
                showListener?.onAdClosed()
            }

            override fun onAdFailedToShowFullScreenContent(adError: AdError) {
                AnalyticsUtils.logAdEvent(
                    placement,
                    AnalyticsUtils.AdEvent.SHOW_FAIL,
                    adError.code,
                    adError.message
                )
                InstAdCacheManager.instance.remove(placement)
                showListener?.onAdShowFailed(adError.toString())
                Log.d(AdsInsUtil.Placement.TAG, "广告 $placement 展示失败->${adError}")
            }

            override fun onAdClicked() {
                showListener?.onAdClicked()
            }

            override fun onAdImpression() {
                // 曝光回调
            }
        }

        interstitialAd.show(activity)
    }
}
