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.LoadAdError
import com.google.android.gms.ads.rewarded.RewardedAd
import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback
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 AdmobRewardRequestImpl : IAdFormatRequest {

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

                override fun onAdFailedToLoad(p0: LoadAdError) {
                    printAdInfo(adUnitBean, p0.responseInfo)
                    if (it.isActive) {
                        it.resume(AdResult.Fail(adUnitBean, AdLoadCode.FAIL, p0.message))
                    }
                }

                override fun onAdLoaded(p0: RewardedAd) {
                    printAdInfo(adUnitBean, p0.responseInfo)
                    if (it.isActive) {
                        it.resume(
                            AdResult.Success(
                                p0,
                                adUnitBean, AdLoadCode.SUCCESS, "AdMob激励广告加载成功"
                            )
                        )
                    }
                }
            }
            val adRequest = com.google.android.gms.ads.AdRequest.Builder()
                .build()

            RewardedAd.load(context, adUnitBean.adUnitId, adRequest, listener)
        }
    }

}
