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.MaxError
import com.applovin.mediation.nativeAds.MaxNativeAdListener
import com.applovin.mediation.nativeAds.MaxNativeAdLoader
import com.applovin.mediation.nativeAds.MaxNativeAdView
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:
 * @author: LiuXiaoLong
 * @date: 2022/11/11
 * description: AppLovinMax 原生模板广告加载类
 */
class AppLovinMaxNativeTemplateRequestImpl : 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 maxNativeAdLoader = MaxNativeAdLoader(adUnitBean.adUnitId, context)

            val listener = object : MaxNativeAdListener() {
                override fun onNativeAdLoaded(maxNativeAdView: MaxNativeAdView?, p1: MaxAd?) {
                    super.onNativeAdLoaded(maxNativeAdView, p1)
                    printAdInfo(adUnitBean)
                    //这里会保存下三个值， 用于处理destroy
                    it.isActiveResult(AdResult.Success(adBean = adUnitBean, adObject = Triple<MaxNativeAdLoader, MaxNativeAdView?, MaxAd?>(maxNativeAdLoader, maxNativeAdView, p1), msg = "AppLovinMax广告-原生模板-加载成功"))
                }

                override fun onNativeAdClicked(p0: MaxAd?) {
                    super.onNativeAdClicked(p0)
                }

                override fun onNativeAdLoadFailed(p0: String?, p1: MaxError?) {
                    super.onNativeAdLoadFailed(p0, p1)
                    printAdFailInfo(adUnitBean, p1?.code?:0, p1?.message)
                    it.isActiveResult(AdResult.Fail(adUnitBean, msg = "AppLovinMax广告-原生模板-加载失败"))
                }

                override fun onNativeAdExpired(p0: MaxAd?) {
                    super.onNativeAdExpired(p0)
                }
            }

            maxNativeAdLoader.setNativeAdListener(listener)
            maxNativeAdLoader.loadAd()
        }
    }

}