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

import android.content.Context
import com.bytedance.sdk.openadsdk.*
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
import kotlin.coroutines.resume

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/13
 * description:穿山甲激励广告加载
 */
class CSJRewardRequestImpl : IAdFormatRequest {
    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {
        return suspendCancellableCoroutine {

            val adSlot = AdSlot.Builder()
                .setCodeId(adUnitBean.adUnitId)
                .setAdCount(1)
                .setOrientation(TTAdConstant.VERTICAL)
                .setAdLoadType(TTAdLoadType.PRELOAD)
                .build()

            TTAdSdk.getAdManager().createAdNative(context)
                .loadRewardVideoAd(adSlot, object : TTAdNative.RewardVideoAdListener {
                    override fun onError(code: Int, p1: String?) {
                        printAdFailInfo(adUnitBean, code, p1)
                        it.isActiveResult(AdResult.Fail(adBean = adUnitBean, msg = p1 ?: "穿山甲广告-激励视频-加载失败"))
                    }

                    override fun onRewardVideoAdLoad(p0: TTRewardVideoAd?) {
                    }

                    override fun onRewardVideoCached() {

                    }

                    override fun onRewardVideoCached(p0: TTRewardVideoAd?) {
                        printAdInfo(adUnitBean)
                        it.resume(AdResult.Success(adBean = adUnitBean, adObject = p0, msg = "穿山甲广告-激励视频-缓存加载成功"))
                    }
                })
        }
    }
}