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

import android.content.Context
import com.bytedance.sdk.openadsdk.*
import com.composition.android.ad.csj.util.printAdFailInfo
import com.composition.android.ad.csj.util.printAdInfo
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 kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

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

            val adSlot = AdSlot.Builder()
                .setCodeId(adUnitBean.adUnitId)
                .setSupportDeepLink(true)
                .setAdCount(1)
                .setOrientation(TTAdConstant.VERTICAL)
                .setAdLoadType(TTAdLoadType.PRELOAD)
                .setExpressViewAcceptedSize(1080F, 1920F)
                .build()

            TTAdSdk.getAdManager().createAdNative(context)
                .loadFullScreenVideoAd(adSlot, object : TTAdNative.FullScreenVideoAdListener{
                    override fun onError(p0: Int, p1: String?) {
                        printAdFailInfo(p0, p1)
                        if (it.isActive) {
                            it.resume(AdResult.Fail(adUnitBean, msg = p1?:"穿山甲模板插屏广告加载失败，code:${p0}"))
                        }
                    }

                    override fun onFullScreenVideoAdLoad(p0: TTFullScreenVideoAd?) {
                        printAdInfo(adUnitBean)
                        if (it.isActive){
                            if (p0 != null){
                                it.resume(AdResult.Success(adBean = adUnitBean, adObject = p0, msg = "穿山甲模板插屏广告加载成功"))
                            }else{
                                it.resume(AdResult.Fail(adUnitBean, msg = "穿山甲模板插屏广告加载失败，adList为空"))
                            }
                        }
                    }

                    override fun onFullScreenVideoCached() {
                    }

                    override fun onFullScreenVideoCached(p0: TTFullScreenVideoAd?) {
                        printAdInfo(adUnitBean)
                        if (it.isActive){
                            if (p0 != null){
                                it.resume(AdResult.Success(adBean = adUnitBean, adObject = p0, msg = "穿山甲模板插屏广告加载成功"))
                            }else{
                                it.resume(AdResult.Fail(adUnitBean, msg = "穿山甲模板插屏广告加载失败，adList为空"))
                            }
                        }
                    }
                })
        }
    }
}