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 com.convenient.android.common.extension.getScreenHeight
import com.convenient.android.common.extension.getScreenHeightDp
import com.convenient.android.common.extension.getScreenWidth
import com.convenient.android.common.extension.getScreenWidthDp
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * @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 = context.getScreenWidthDp()
            val splashWidthPx: Int = context.getScreenWidth()
            val screenHeightPx: Int = context.getScreenHeight()
            val screenHeightDp: Float = context.getScreenHeightDp()

            // 开屏高度 = 屏幕高度 - 下方预留的高度，demo中是预留了屏幕高度的1/5，因此开屏高度传入 屏幕高度*4/5
            val splashHeightDp: Float = screenHeightDp * 4 / 5f
            val splashHeightPx: Int = (screenHeightPx * 4 / 5f).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(p0, p1)
                        if (it.isActive){
                            it.resume(AdResult.Fail(adBean = adUnitBean, msg = p1?:"穿山甲开屏广告加载失败"))
                        }
                    }

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

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


    }
}