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.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import kotlinx.coroutines.suspendCancellableCoroutine

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/5
 * description: Admob插屏广告请求实现
 */
class AdmobInterstitialRequestImpl : IAdFormatRequest {

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

        return suspendCancellableCoroutine {
            val listener: InterstitialAdLoadCallback = object : InterstitialAdLoadCallback() {
                override fun onAdLoaded(p0: InterstitialAd) {
                    printAdInfo(adUnitBean)
                    it.isActiveResult(
                        AdResult.Success(
                            adObject = p0,
                            adBean = adUnitBean,
                            code = AdLoadCode.SUCCESS,
                            msg = "Admob广告-插屏-加载成功"
                        )
                    )
                }

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

            InterstitialAd.load(
                context, adUnitBean.adUnitId,
                com.google.android.gms.ads.AdRequest.Builder()
                    .build(),
                listener
            )
        }
    }
}
