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

import android.app.Activity
import android.content.Context
import android.util.Log
import com.all.pdfreader.pdf.reader.util.AnalyticsUtils
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdLoader
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.nativead.NativeAd

object NativeAdCache {
    private var cachedAd: NativeAd? = null

    fun load(
        context: Context,
        placement: AdsInsUtil.AdPlacement,
        onAdLoaded: (() -> Unit)? = null,
        onAdFailedToLoad: (() -> Unit)? = null
    ) {
        if (cachedAd != null) {
            onAdLoaded?.invoke()
            return
        }
        val adUnitId = AdsInsUtil.adUnitIdMap[placement] ?: run {
            val errorMsg = "No AdUnitId for $placement"
            Log.d(AdsInsUtil.Placement.TAG, "没找到对应的广告ID->$placement")
            onAdFailedToLoad?.invoke()
            return
        }
        AnalyticsUtils.logAdEvent(placement, AnalyticsUtils.AdEvent.REQ)
        val adLoader = AdLoader.Builder(context, adUnitId)
            .forNativeAd { ad ->
                if (context is Activity) {
                    if (context.isFinishing || context.isDestroyed) {
                        ad.destroy()
                        return@forNativeAd
                    }
                }
                cachedAd?.destroy()
                cachedAd = ad
                onAdLoaded?.invoke()
            }
            .withAdListener(object : AdListener() {
                override fun onAdFailedToLoad(error: LoadAdError) {
                    cachedAd = null
                    onAdFailedToLoad?.invoke()
                    Log.d(AdsInsUtil.Placement.TAG, "$placement 广告加载失败 ${error.message}")
                    AnalyticsUtils.logAdEvent(
                        placement,
                        AnalyticsUtils.AdEvent.LOAD_FAIL,
                        error.code,
                        error.message
                    )
                }

                override fun onAdLoaded() {
                    Log.d(AdsInsUtil.Placement.TAG, "$placement 广告加载成功")
                    AnalyticsUtils.logAdEvent(placement, AnalyticsUtils.AdEvent.LOADED)
                }
            })
            .build()

        adLoader.loadAd(AdRequest.Builder().build())
    }

    fun getAd(): NativeAd? = cachedAd

    fun clear() {
        cachedAd?.destroy()
        cachedAd = null
    }
}