package com.composition.android.ad.applovinmax

import android.content.Context
import com.composition.android.ad.applovinmax.load.AppLovinMaxLoader
import com.composition.android.lib.ad.AdLoad
import com.composition.android.lib.ad.AdUnitConfigManager
import com.composition.android.lib.ad.basic.AdResult
import com.composition.android.lib.ad.basic.Advertisers
import com.composition.android.lib.ad.basic.NativeAdViewHolder
import com.composition.android.lib.ad.bean.AdUnitBean
import com.composition.android.lib.ad.factory.AdLoaderFactory
import com.composition.android.lib.ad.util.adLog
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.flow

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/11/18
 * description:
 */


/**
 * 加载原生广告扩展类， APPLovin原生广告需要先传入创建的自定义布局内容进行加载
 * @param context 上下文，要是activity类型
 * @param adSlotNames 广告位名称
 * @param 原生广告自定义布局内容配置
 */
suspend fun AdLoad.loadAd(context: Context, vararg adSlotNames: String, nativeAdViewHolder: NativeAdViewHolder): Flow<AdResult> {
    return flow<AdResult> {
        val adUnitBeans = AdUnitConfigManager.instance.getAdUnitBySlotName(adSlotNames.toList())
        if (adUnitBeans.isNullOrEmpty()) {
            adLog(msg = "广告单元配置为空")
            emit(AdResult.Fail(adBean = AdUnitBean.emptyAdUnitBean(), msg = "AdUnitBeans 为空"))
            return@flow
        }
        for (bean in adUnitBeans) {
            if (bean.getAdvertisers() == Advertisers.AppLovinMax) {
                (AdLoaderFactory.getAdLoader(bean) as? AppLovinMaxLoader)?.loadNativeAd(context, bean, nativeAdViewHolder)?.let {
                    emit(it)
                } ?: emit(AdResult.Fail(bean, msg = "AppLovinMax广告-原生-加载失败"))
            } else {
                emit(AdLoaderFactory.getAdLoader(bean).load(context, bean))
            }
        }
    }
}

suspend fun AdLoad.preloadAd(context: Context, vararg adSlotNames: String, nativeAdViewHolder: NativeAdViewHolder){
    loadAd(context, *adSlotNames, nativeAdViewHolder = nativeAdViewHolder)
        .collect{
            if (it is AdResult.Success){
                AdLoad.addToCache(it)
            }
        }
}