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

import android.content.Context
import com.composition.android.lib.ad.AdManager
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.adLogE
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.appopen.AppOpenAd
import com.composition.android.ad.admob.util.printAdInfo
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/5
 * description:
 */
class AdmobAppOpenRequestImpl : IAdFormatRequest {

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

            val listener: AppOpenAd.AppOpenAdLoadCallback =
                object : AppOpenAd.AppOpenAdLoadCallback() {
                    override fun onAdFailedToLoad(p0: LoadAdError) {
                        adLogE(AdManager.TAG, p0.message)
                        if (it.isActive) {
                            it.resume(
                                AdResult.Fail(
                                    adUnitBean,
                                    AdLoadCode.FAIL,
                                    p0.message
                                )
                            )
                        }

                    }
                    override fun onAdLoaded(p0: AppOpenAd) {
                        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()
            AppOpenAd.load(context, adUnitBean.adUnitId, adRequest, AppOpenAd.APP_OPEN_AD_ORIENTATION_PORTRAIT, listener)

        }
    }
}