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

import android.content.Context
import com.composition.android.ad.admob.util.getFailedCodeInfo
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.rewardedinterstitial.RewardedInterstitialAd
import com.google.android.gms.ads.rewardedinterstitial.RewardedInterstitialAdLoadCallback
import kotlinx.coroutines.suspendCancellableCoroutine

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/5
 * description:Admob激励插屏广告加载实现类
 */
class AdmobRewardInterstitialRequestImpl : IAdFormatRequest {


    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {
        return suspendCancellableCoroutine {
            val listener: RewardedInterstitialAdLoadCallback =
                object : RewardedInterstitialAdLoadCallback() {
                    override fun onAdLoaded(p0: RewardedInterstitialAd) {
                        printAdInfo(adUnitBean)
                        it.isActiveResult(
                            AdResult.Success(
                                adBean = adUnitBean,
                                adObject = p0,
                                code = AdLoadCode.SUCCESS,
                                msg = "Admob广告-激励-加载成功"
                            )
                        )
                    }

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

            val adRequest = com.google.android.gms.ads.AdRequest.Builder()
                .build()

            RewardedInterstitialAd.load(context, adUnitBean.adUnitId, adRequest, listener)

        }
    }
}