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

import android.content.Context
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.TTAdLoadType
import com.bytedance.sdk.openadsdk.TTAdNative
import com.bytedance.sdk.openadsdk.TTAdSdk
import com.bytedance.sdk.openadsdk.TTNativeAd
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

class GMNativeRequestImpl : IAdFormatRequest {

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

        return suspendCancellableCoroutine {

            val adSize = if (adUnitBean.adSize != null && adUnitBean.adSize is GMAdImageSize) {
                val size = adUnitBean.adSize as  GMAdImageSize
                size.gmAdSize
            } else {
                640 to 320
            }
            val adSlot = AdSlot.Builder()
                .setCodeId(adUnitBean.adUnitId)
                .setSupportDeepLink(true)
                .setAdCount(1)
                .setImageAcceptedSize(adSize.first, adSize.second)
                .setNativeAdType(AdSlot.TYPE_BANNER)
                .setAdLoadType(TTAdLoadType.PRELOAD)
                .build()

            TTAdSdk.getAdManager().createAdNative(context)
                .loadNativeAd(adSlot, object : TTAdNative.NativeAdListener {
                    override fun onError(p0: Int, p1: String?) {
                        printAdFailInfo(adUnitBean, p0, p1)
                        it.isActiveResult(AdResult.Fail(adUnitBean, msg = p1 ?: "GroMore广告-原生-加载失败"))
                    }

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