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.*
import kotlinx.coroutines.suspendCancellableCoroutine

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/13
 * description:穿山甲开屏广告加载类
 */
class CSJAppOpenRequestImpl : IAdFormatRequest {
    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {

        return suspendCancellableCoroutine {
            //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
            val splashWidthDp: Float = getScreenWidthDp(context)
            val splashWidthPx: Int = getScreenWidth(context)
            val screenHeightPx: Int = getScreenHeight(context)
            val screenHeightDp: Float = getScreenHeightDp(context)

            // 开屏高度 = 屏幕高度 - 下方预留的高度，demo中是预留了屏幕高度的1/5，因此开屏高度传入 屏幕高度*4/5
            val splashHeightDp: Float = screenHeightDp * 4 / 4f
            val splashHeightPx: Int = (screenHeightPx * 4 / 4f).toInt()

            val adSlot = AdSlot.Builder()
                .setCodeId(adUnitBean.adUnitId)
                .setExpressViewAcceptedSize(splashWidthDp, splashHeightDp)
                .setImageAcceptedSize(splashWidthPx, splashHeightPx)
                .setAdLoadType(TTAdLoadType.PRELOAD)
                .build()

            TTAdSdk.getAdManager().createAdNative(context)
                .loadSplashAd(adSlot, object : TTAdNative.SplashAdListener {
                    override fun onError(p0: Int, p1: String?) {
                        printAdFailInfo(adUnitBean, p0, p1)
                        it.isActiveResult(AdResult.Fail(adBean = adUnitBean, msg = p1 ?: "穿山甲广告-开屏-加载失败"))
                    }

                    override fun onTimeout() {
                        printAdFailInfo(adUnitBean, 0, "加载超时")
                        it.isActiveResult(AdResult.Fail(adBean = adUnitBean, msg = "穿山甲广告-开屏-加载失败,请求超时"))
                    }

                    override fun onSplashAdLoad(p0: TTSplashAd?) {
                        printAdInfo(adUnitBean)
                        it.isActiveResult(AdResult.Success(adBean = adUnitBean, adObject = p0, msg = "穿山甲广告-开屏-加载成功"))
                    }
                })
        }


    }
}