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

import android.app.Activity
import android.content.Context
import android.view.ViewGroup
import android.widget.RelativeLayout
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdViewAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxAdView
import com.applovin.mediation.nativeAds.MaxNativeAdLoader
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.*
import com.kdanmobile.android.ad.applovinmax.R
import kotlinx.coroutines.suspendCancellableCoroutine

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/11/11
 * description: AppLovinMax 横幅广告加载类
 */
class AppLovinMaxBannerRequestImpl : 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 maxAdView = MaxAdView(adUnitBean.adUnitId, context)
            //先关闭自动刷新，当请求成功再开启自动刷新功能
            //这样做是为了统一逻辑， BannerView中会有重试， app lovin会大概间隔10秒刷新一次广告， 每次都会调用onAdLoaded
            maxAdView.setExtraParameter("allow_pause_auto_refresh_immediately", "true")
            maxAdView.stopAutoRefresh()
            val listener = object : MaxAdViewAdListener {
                override fun onAdLoaded(ad: MaxAd?) {
                    printAdInfo(adUnitBean)
                    //更新view的高度
                    val width = ViewGroup.LayoutParams.MATCH_PARENT
                    val heightDp = if (ad != null) {
                        ad.size?.height ?: 0
                    } else {
                        context.resources.getDimensionPixelSize(R.dimen.app_lovin_banner_height)
                    }

                    val heightPx = dp2px(context, heightDp.toFloat())
                    maxAdView.layoutParams = RelativeLayout.LayoutParams(width, heightPx)

                    //返回结果 返回一次之后 isActive为 false
                    it.isActiveResult(AdResult.Success(adObject = maxAdView, adUnitBean, msg = "AppLovinMax广告-横幅-加载成功"))
                }

                override fun onAdDisplayed(ad: MaxAd?) {
//                    adLog(TAG, "广告展示")
                }

                override fun onAdHidden(ad: MaxAd?) {

                }

                override fun onAdClicked(ad: MaxAd?) {
                    //这里没有错，横幅广告点击才算广告打开

                }

                override fun onAdLoadFailed(adUnitId: String?, error: MaxError?) {
                    printAdFailInfo(adUnitBean, error?.code ?: 0, error?.message)

                    error?.waterfall?.let {
                        for (networkRespons in it.networkResponses) {
                            adLog(AdManager.TAG, networkRespons.error.code.toString())
                            adLog(AdManager.TAG, networkRespons.error.message)
                        }
                    }
                    it.isActiveResult(AdResult.Fail(adUnitBean, msg = "AppLovinMax广告-横幅-加载失败"))
                }

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

                override fun onAdExpanded(ad: MaxAd?) {
                }

                override fun onAdCollapsed(ad: MaxAd?) {

                }
            }
            maxAdView.setListener(listener)
            //设置返回 适配器广告的尺寸
            maxAdView.setExtraParameter("adaptive_banner", "true")
            maxAdView.loadAd()
        }
    }

}