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.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback

class AdInstLoad(
    private val activity: Activity,
    private val placement: AdsInsUtil.AdPlacement,
    private val adLoadListener: LoadListener?
) {

    init {
        loadAd()
    }

    private fun loadAd() {
        Log.d(AdsInsUtil.Placement.TAG,"广告 $placement 开始加载")
        // 是否存在缓存广告、展示安全
        val cachedAd = InstAdCacheManager.instance.getAdCache(placement)
        if (cachedAd != null) {
            Log.d(AdsInsUtil.Placement.TAG,"广告存在缓存，跳过加载，返回成功")
            //缓存广告有效，跳过加载，返回成功
            adLoadListener?.loaded(cachedAd)
            return
        }

        // 如果正在加载（其他地方已 load） 加入等待队列
        if (InstAdCacheManager.instance.isLoading(placement)) {
            Log.d(AdsInsUtil.Placement.TAG,"广告 $placement 正在加载中，加入等待队列")
            InstAdCacheManager.instance.addPendingListener(placement, adLoadListener)
            return
        }

        // 本次为真正开始加载 标记 loading（并加入当前 listener）
        InstAdCacheManager.instance.markLoading(placement, adLoadListener)

        val adUnitId = AdsInsUtil.adUnitIdMap[placement] ?: run {
            val errorMsg = "No AdUnitId for $placement"
            Log.d(AdsInsUtil.Placement.TAG,"没找到对应的广告ID->$placement")
            InstAdCacheManager.instance.notifyFail(placement, errorMsg)
            return
        }
        AnalyticsUtils.logAdEvent(placement, AnalyticsUtils.AdEvent.REQ)
        Log.d(AdsInsUtil.Placement.TAG,"adUnitId->$adUnitId")
        InterstitialAd.load(
            activity,
            adUnitId,
            AdRequest.Builder().build(),
            object : InterstitialAdLoadCallback() {
                override fun onAdLoaded(ad: InterstitialAd) {
                    Log.d(AdsInsUtil.Placement.TAG,"广告 $placement 加载成功")
                    InstAdCacheManager.instance.setAdCache(placement, ad)
                    AnalyticsUtils.logAdEvent(placement, AnalyticsUtils.AdEvent.LOADED)
                    InstAdCacheManager.instance.notifySuccess(placement, ad)
                }

                override fun onAdFailedToLoad(adError: LoadAdError) {
                    Log.d(AdsInsUtil.Placement.TAG,"广告 $placement 加载失败")
                    AnalyticsUtils.logAdEvent(
                        placement,
                        AnalyticsUtils.AdEvent.LOAD_FAIL,
                        adError.code,
                        adError.message
                    )
                    InstAdCacheManager.instance.notifyFail(placement, adError.toString())
                }
            },
        )
    }
}