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

import android.app.Activity
import android.content.Context
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxInterstitialAd
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.isActiveResult
import com.composition.android.lib.ad.util.printAdFailInfo
import com.composition.android.lib.ad.util.printAdInfo
import kotlinx.coroutines.suspendCancellableCoroutine

/**
 * @classname:AppLovinMaxAppOpenRequestImpl
 * @author: LiuXiaoLong
 * @date: 2022/11/11
 * description: AppLovinMax 插屏广告加载类
 */
class AppLovinMaxInterstitialRequestImpl : IAdFormatRequest {


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

        return suspendCancellableCoroutine {

            if (context !is Activity) {
                printAdFailInfo(adUnitBean, 0, "AppLovinMax广告，context必须为Activity类型")
                it.isActiveResult(AdResult.Fail(adUnitBean, msg = "AppLovinMax广告-插屏-加载失败，context必须为Activity"))
                return@suspendCancellableCoroutine
            }

            val interstitialAd = MaxInterstitialAd(adUnitBean.adUnitId, context)
            interstitialAd.setListener(object : MaxAdListener{
                override fun onAdLoaded(ad: MaxAd?) {
                    printAdInfo(adUnitBean)
                    it.isActiveResult(AdResult.Success(adObject = interstitialAd, adBean = adUnitBean, msg = "AppLovinMax广告-插屏-加载成功"))
                }

                override fun onAdDisplayed(ad: MaxAd?) {

                }

                override fun onAdHidden(ad: MaxAd?) {
                }

                override fun onAdClicked(ad: MaxAd?) {
                }

                override fun onAdLoadFailed(adUnitId: String?, error: MaxError?) {
                    printAdFailInfo(adUnitBean, error?.code?:0, error?.message)
                    it.isActiveResult(AdResult.Fail(adUnitBean, msg = "AppLovinMax广告-插屏-加载失败"))
                }

                override fun onAdDisplayFailed(ad: MaxAd?, error: MaxError?) {
                }
            })
            interstitialAd.loadAd()

        }
    }
}