package com.simplecleaner.app.business.ads.admob

import android.content.Context
import androidx.annotation.LayoutRes
import com.google.android.gms.ads.nativead.NativeAd
import com.simplecleaner.app.business.ads.NativeParentView
import com.simplecleaner.app.business.ads.LimitUtils
import com.simplecleaner.app.business.ads.AdsType
import com.simplecleaner.app.utils.LogEx

/**
 * 原生广告渲染器
 */
class NativeAdRenderer {
    
    private val TAG = "NativeAdRenderer"
    
    /**
     * 渲染原生广告
     */
    fun renderAd(
        nativeAd: NativeAd,
        parent: NativeParentView,
        @LayoutRes layout: Int,
        admobEvent: AdmobEvent,
        onSuccess: ((NativeAd) -> Unit)? = null,
        onError: ((String) -> Unit)? = null
    ) {
        try {
            LogEx.logDebug(TAG, "Rendering native ad")
            
            // 检查展示限制
            if (!LimitUtils.isShowNative(AdsType.NATIVE, admobEvent)) {
                LogEx.logDebug(TAG, "Show limit exceeded")
                onError?.invoke(NativeAdConfig.ErrorCode.SHOW_LIMIT_EXCEEDED)
                return
            }
            
            // 设置广告到父视图
            parent.isAdShowed = true
            parent.setNativeAd(nativeAd, layout)
            
            // 上报展示事件
            admobEvent.showAd(nativeAd.responseInfo)
            
            // 增加原生广告展示数量
            LimitUtils.addNativeDisplayNum()
            
            LogEx.logDebug(TAG, "Native ad rendered successfully")
            onSuccess?.invoke(nativeAd)
            
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Error rendering native ad: ${e.message}")
            onError?.invoke(e.message ?: "Unknown rendering error")
        }
    }
    
    /**
     * 检查广告是否有效
     */
    fun isAdValid(nativeAd: NativeAd?): Boolean {
        return try {
            nativeAd?.let { ad ->
                ad.headline?.isNotEmpty() == true || ad.body?.isNotEmpty() == true
            } ?: false
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Error checking ad validity: ${e.message}")
            false
        }
    }
    
    /**
     * 销毁广告
     */
    fun destroyAd(nativeAd: NativeAd?) {
        try {
            nativeAd?.destroy()
            LogEx.logDebug(TAG, "Native ad destroyed")
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Error destroying native ad: ${e.message}")
        }
    }
} 