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

import android.content.Context
import com.bytedance.sdk.openadsdk.*
import com.composition.android.ad.gromore.impl.GMAdImageSize
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 kotlinx.coroutines.suspendCancellableCoroutine

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/15
 * description: GroMore Banner广告加载类
 */
class GMBannerRequestImpl : IAdFormatRequest {
    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {
        return suspendCancellableCoroutine {
            val size = if (adUnitBean.adSize is GMAdImageSize) (adUnitBean.adSize as GMAdImageSize).gmAdSize else 600 to 90
            val adSlot = AdSlot.Builder()
                .setCodeId(adUnitBean.adUnitId)
                .setAdCount(1)
                .setExpressViewAcceptedSize(size.first.toFloat(), size.second.toFloat())
                .setAdLoadType(TTAdLoadType.PRELOAD)
                .build()

            TTAdSdk.getAdManager().createAdNative(context)
                .loadBannerExpressAd(adSlot, object : TTAdNative.NativeExpressAdListener {
                    override fun onError(p0: Int, p1: String?) {
                        printAdFailInfo(adUnitBean, p0, p1)
                        it.isActiveResult(AdResult.Fail(adUnitBean, msg = p1 ?: "GroMore-横幅-加载失败"))
                    }

                    override fun onNativeExpressAdLoad(p0: MutableList<TTNativeExpressAd>?) {
                        printAdInfo(adUnitBean)
                        if (p0.isNullOrEmpty().not()) {
                            it.isActiveResult(AdResult.Success(adBean = adUnitBean, adObject = p0?.get(0), msg = "GroMore-横幅-加载成功"))
                        } else {
                            printAdFailInfo(adUnitBean, 0, "SDK返回的广告实例为空")
                            it.isActiveResult(AdResult.Fail(adUnitBean, msg = "GroMore-横幅-加载失败, 返回的广告实例为空"))
                        }
                    }
                })
        }
    }
}