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

import android.content.Context
import androidx.annotation.LayoutRes
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.nativead.NativeAd
import com.simplecleaner.app.MyApplication
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 NativeAdManager {
    
    private val TAG = "NativeAdManager"
    
    // 组件实例
    private val cache = NativeAdCache()
    private val loader = NativeAdLoader()
    private val renderer = NativeAdRenderer()
    
    /**
     * 加载原生广告
     */
    fun loadAd(
        context: Context,
        admobEvent: AdmobEvent,
        showAction: ((ad: NativeAd) -> Unit)? = null
    ) {
        try {
            LogEx.logDebug(TAG, "Loading native ad")
            
            // 检查广告展示限制
            if (!LimitUtils.isAdShow(AdsType.NATIVE, admobEvent)) {
                LogEx.logDebug(TAG, "Ad show limit exceeded")
                return
            }
            
            loader.loadAd(
                context = context,
                admobEvent = admobEvent,
                onSuccess = { nativeAd ->
                    LogEx.logDebug(TAG, "Ad loaded successfully")
                    
                    if (showAction != null) {
                        // 直接展示广告
                        showAction.invoke(nativeAd)
                    } else {
                        // 添加到缓存
                        if (!cache.addToCache(nativeAd)) {
                            LogEx.logDebug(TAG, "Failed to add ad to cache, destroying")
                            renderer.destroyAd(nativeAd)
                        }
                    }
                },
                onError = { error ->
                    LogEx.logDebug(TAG, "Ad load failed: ${error.message}")
                }
            )
            
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Error in loadAd: ${e.message}")
        }
    }
    
    /**
     * 展示原生广告
     */
    fun show(
        admobEvent: AdmobEvent,
        parent: NativeParentView,
        @LayoutRes layout: Int,
        nativeCallBack: ((Any?) -> Unit)? = null
    ) {
        try {
            LogEx.logDebug(TAG, "Showing native ad")
            
            // 检查广告展示限制
            if (!LimitUtils.isAdShow(AdsType.NATIVE, admobEvent)) {
                LogEx.logDebug(TAG, "Ad show limit exceeded")
                cache.clearCache()
                nativeCallBack?.invoke(null)
                return
            }
            
            // 检查展示限制
            if (!LimitUtils.isShowNative(AdsType.NATIVE, admobEvent)) {
                LogEx.logDebug(TAG, "Show native limit exceeded")
                nativeCallBack?.invoke(null)
                return
            }
            
            admobEvent.adPrepareShow()
            
            // 尝试从缓存获取广告
            var nativeAd = cache.getFromCache()
            
            if (nativeAd != null) {
                // 使用缓存的广告
                LogEx.logDebug(TAG, "Using cached ad")
                showAd(nativeAd, parent, layout, admobEvent, nativeCallBack)
            } else {
                // 缓存中没有广告，重新加载
                LogEx.logDebug(TAG, "No cached ad available, loading new ad")
                loadAd(
                    context = parent.context,
                    admobEvent = admobEvent
                ) { ad ->
                    showAd(ad, parent, layout, admobEvent, nativeCallBack)
                }
            }
            
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Error in show: ${e.message}")
            nativeCallBack?.invoke(null)
        }
    }
    
    /**
     * 展示广告的具体实现
     */
    private fun showAd(
        nativeAd: NativeAd,
        parent: NativeParentView,
        @LayoutRes layout: Int,
        admobEvent: AdmobEvent,
        nativeCallBack: ((Any?) -> Unit)?
    ) {
        renderer.renderAd(
            nativeAd = nativeAd,
            parent = parent,
            layout = layout,
            admobEvent = admobEvent,
            onSuccess = { ad ->
                LogEx.logDebug(TAG, "Ad shown successfully")
                nativeCallBack?.invoke(ad)
                
                // 预加载下一个广告
                preloadNextAd()
            },
            onError = { error ->
                LogEx.logDebug(TAG, "Failed to show ad: $error")
                nativeCallBack?.invoke(null)
            }
        )
    }
    
    /**
     * 预加载下一个广告
     */
    private fun preloadNextAd() {
        try {
            loadAd(
                context = MyApplication.appContext,
                admobEvent = AdmobEvent(NativeAdConfig.Event.AD_UNIT_NAME, NativeAdConfig.Event.PRELOAD_FROM)
            )
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Error preloading next ad: ${e.message}")
        }
    }
    
    /**
     * 预加载广告
     */
    fun preloadAd(context: Context) {
        try {
            loader.preloadAd(context)
        } catch (e: Exception) {
            LogEx.logDebug(TAG, "Error preloading ad: ${e.message}")
        }
    }
    
    /**
     * 清空缓存
     */
    fun clearCache() {
        cache.clearCache()
    }
    
    /**
     * 获取缓存统计信息
     */
    fun getCacheStats(): NativeAdCache.CacheStats {
        return cache.getCacheStats()
    }
    
    /**
     * 检查是否有可用广告
     */
    fun hasAvailableAd(): Boolean {
        return cache.hasAvailableAd()
    }
    
    /**
     * 获取缓存大小
     */
    fun getCacheSize(): Int {
        return cache.getCacheSize()
    }
} 