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

import android.app.Activity
import android.content.Context
import com.beizi.fusion.SplashAd
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/16
 * description:GroMore开屏广告加载类
 */
class GMAppOpenRequestImpl : IAdFormatRequest {
    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {
        return suspendCancellableCoroutine {
            if (context is Activity) {
                val adSlot = AdSlot.Builder()
                    .setCodeId(adUnitBean.adUnitId)
                    .setImageAcceptedSize(getScreenWidth(context), getScreenHeight(context))
                    .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 ?: "GroMore-开屏-加载失败"))
                        }

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

                        override fun onSplashAdLoad(splashAd : TTSplashAd?) {
                            printAdInfo(adUnitBean)
                            it.isActiveResult(AdResult.Success(adBean = adUnitBean, adObject = splashAd, msg = "GroMore-开屏-加载成功"))
                        }
                    })
            } else {
                printAdFailInfo(adUnitBean, 0, "GroMore广告-开屏-加载失败：context需要为Activity")
                it.isActiveResult(AdResult.Fail(adUnitBean, msg = "GroMore广告-开屏-加载失败：context需要为Activity"))
            }
        }
    }
}