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.composition.android.lib.ad.util.isActiveResult
import com.composition.android.lib.ad.util.printAdFailInfo
import com.composition.android.lib.ad.util.printAdInfo
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
import kotlinx.coroutines.suspendCancellableCoroutine

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/5
 * description: Admob激励广告实现
 */
class AdmobRewardRequestImpl : IAdFormatRequest {

    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {
        return suspendCancellableCoroutine {
            val listener: RewardedAdLoadCallback = object : RewardedAdLoadCallback() {

                override fun onAdFailedToLoad(p0: LoadAdError) {
                    printAdFailInfo(adUnitBean, p0.code, p0.message)
                    it.isActiveResult(AdResult.Fail(adUnitBean, AdLoadCode.FAIL, p0.message))
                }

                override fun onAdLoaded(p0: RewardedAd) {
                    printAdInfo(adUnitBean)
                    it.isActiveResult(AdResult.Success(p0, adUnitBean, AdLoadCode.SUCCESS, "Admob广告-激励-加载成功"))
                }
            }
            val adRequest = com.google.android.gms.ads.AdRequest.Builder()
                .build()
            RewardedAd.load(context, adUnitBean.adUnitId, adRequest, listener)
        }
    }

}
