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

import android.app.Activity
import android.content.Context
import com.bytedance.msdk.api.AdError
import com.bytedance.msdk.api.v2.GMAdSize
import com.bytedance.msdk.api.v2.ad.banner.GMBannerAd
import com.bytedance.msdk.api.v2.ad.banner.GMBannerAdLoadCallback
import com.bytedance.msdk.api.v2.slot.GMAdSlotBanner
import com.composition.android.ad.gromore.load.impl.GMBannerAdSize
import com.composition.android.ad.gromore.load.util.GMSettingConfig
import com.composition.android.ad.gromore.load.util.printAdFailInfo
import com.composition.android.ad.gromore.load.util.printAdInfo
import com.composition.android.lib.ad.AdManager
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.adLogE
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/15
 * description: GroMore Banner广告加载类
 */
class GMBannerRequestImpl : IAdFormatRequest {

    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {
        return suspendCancellableCoroutine {

            GMSettingConfig.loadAdConfig {

                if (context is Activity) {
                    val mTTBannerViewAd = GMBannerAd(context, adUnitBean.adUnitId)
                    val size = if (adUnitBean.adSize is GMBannerAdSize) (adUnitBean.adSize as GMBannerAdSize).gmAdSize else 600 to 90
                    val slotBanner = GMAdSlotBanner.Builder()
                        .setBannerSize(GMAdSize.BANNER_CUSTOME)
                        .setAllowShowCloseBtn(true)
                        .setImageAdSize(size.first, size.second)
                        .setMuted(true)
                        .build()
                    mTTBannerViewAd.loadAd(slotBanner, object : GMBannerAdLoadCallback {
                        override fun onAdFailedToLoad(p0: AdError) {
                            printAdFailInfo(p0.code, p0.message)
                            if (it.isActive) {
                                it.resume(AdResult.Fail(adUnitBean, msg = p0.message))
                            }
                        }

                        override fun onAdLoaded() {
                            printAdInfo(adUnitBean)
                            if (it.isActive) {
                                it.resume(AdResult.Success(adBean = adUnitBean, adObject = mTTBannerViewAd, msg = "GroMore Banner广告加载成功"))
                            }
                        }
                    })

                } else {
                    adLogE(AdManager.TAG, "GroMore广告加载context需要为Activity")
                    it.resume(AdResult.Fail(adUnitBean, msg = "GroMore广告加载context需要为Activity"))
                }
            }
        }
    }
}