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.ad.nativeAd.GMNativeAd
import com.bytedance.msdk.api.v2.ad.nativeAd.GMNativeAdLoadCallback
import com.bytedance.msdk.api.v2.ad.nativeAd.GMUnifiedNativeAd
import com.bytedance.msdk.api.v2.slot.GMAdOptionUtil
import com.bytedance.msdk.api.v2.slot.GMAdSlotNative
import com.bytedance.sdk.openadsdk.AdSlot
import com.composition.android.ad.gromore.load.util.GMSettingConfig
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.getScreenWidthDp
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlin.coroutines.resume

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/16
 * description: GroMore原生模板广告加载类
 */
class GMNativeTemplateRequestImpl() : IAdFormatRequest {

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

        return suspendCancellableCoroutine {
            if (context is Activity){
                GMSettingConfig.loadAdConfig {

                    val gmNativeAd = GMUnifiedNativeAd(context, adUnitBean.adUnitId)
                    gmNativeAd.loadAd(GMAdSlotNative.Builder()
                        .setAdCount(1)
                        .setGMAdSlotBaiduOption(GMAdOptionUtil.getGMAdSlotBaiduOption().build())
                        .setGMAdSlotGDTOption(GMAdOptionUtil.getGMAdSlotGDTOption().build())
                        .setAdStyleType(AdSlot.TYPE_FEED)
                        .setImageAdSize(context.getScreenWidthDp().toInt(), 340)
                        .build(),
                        object  : GMNativeAdLoadCallback{
                            override fun onAdLoaded(p0: MutableList<GMNativeAd>) {
                                if (it.isActive) {
                                    if (p0.isNullOrEmpty().not()){
                                        it.resume(AdResult.Success(adBean = adUnitBean, adObject = p0.get(0), msg = "GroMore原生模板广告加载成功"))
                                    }else{
                                        it.resume(AdResult.Fail(adUnitBean, msg = "GroMore 原生模板广告"))
                                    }
                                }
                            }
                            override fun onAdLoadedFail(p0: AdError) {
                            }
                        }
                    )
                }

            }else{
                if (it.isActive) {
                    it.resume(AdResult.Fail(adUnitBean, msg = "GroMore 原生广告加载需要context为Activity类型"))
                }
            }

        }

    }
}