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

import android.content.Context
import com.composition.android.ad.admob.impl.AdmobAdSize
import com.composition.android.ad.admob.util.getAdSize
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.AdListener
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.LoadAdError
import kotlinx.coroutines.suspendCancellableCoroutine

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/5
 * description:Admob横幅广告加载实现
 */
class AdmobBannerRequestImpl : IAdFormatRequest {


    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {
        return suspendCancellableCoroutine<AdResult> {
            val adView = AdView(context).apply {
                adUnitId = adUnitBean.adUnitId
                setAdSize(
                    if (adUnitBean.adSize is AdmobAdSize) {
                        (adUnitBean.adSize as AdmobAdSize).size
                    } else {
                        getAdSize(context)
                    }
                )
            }

            val listener: AdListener = object : AdListener() {
                override fun onAdLoaded() {
                    super.onAdLoaded()
                    printAdInfo(adUnitBean)
                    it.isActiveResult(
                        AdResult.Success(
                            adView,
                            adUnitBean,
                            AdLoadCode.SUCCESS,
                            "Admob广告-横幅-加载成功"
                        )
                    )
                }

                override fun onAdFailedToLoad(p0: LoadAdError) {
                    super.onAdFailedToLoad(p0)
                    printAdFailInfo(adUnitBean, p0.code, p0.message)
                    it.isActiveResult(
                        AdResult.Fail(
                            adUnitBean,
                            AdLoadCode.FAIL,
                            p0.message
                        )
                    )
                }
            }
            adView.adListener = listener
            val adRequest = com.google.android.gms.ads.AdRequest.Builder()
                .build()
            adView.loadAd(adRequest)
        }
    }
}