package com.composition.android.ad.admob.load.request

import android.content.Context
import com.composition.android.lib.ad.basic.AdLoadCode
import com.composition.android.lib.ad.basic.AdResult
import com.composition.android.lib.ad.bean.AdUnitBean
import com.composition.android.lib.ad.interfaces.IAdFormatRequest
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.composition.android.ad.admob.util.printAdInfo
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/5
 * description:Admob原生广告加载实现
 */
class AdMobNativeRequestImpl : IAdFormatRequest{


    override suspend fun load(context: Context, adUnitBean : AdUnitBean)  : AdResult{

        return suspendCancellableCoroutine {
            val listener: AdListener = object : AdListener() {
                override fun onAdFailedToLoad(p0: LoadAdError) {
                    printAdInfo(adUnitBean, p0.responseInfo)
                    if (it.isActive) {
                        it.resume(AdResult.Fail(adUnitBean, msg = p0.message))
                    }
                }
            }
            val adLoader = AdLoader.Builder(context, adUnitBean.adUnitId)
                .forNativeAd {nativeAd->
                    printAdInfo(adUnitBean, nativeAd.responseInfo)
                    if (it.isActive) {
                        it.resume(
                            AdResult.Success(
                                nativeAd,
                                adUnitBean,
                                AdLoadCode.SUCCESS,
                                "AdMob 原生广告加载成功"
                            )
                        )
                    }
                }
                .withAdListener(listener).build()
            val adRequest = AdRequest.Builder().build()
            adLoader.loadAd(adRequest)
        }
    }


}