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

import android.content.Context
import com.applovin.mediation.MaxAd
import com.applovin.mediation.MaxAdViewAdListener
import com.applovin.mediation.MaxError
import com.applovin.mediation.ads.MaxAdView
import com.composition.android.lib.ad.AdManager
import com.composition.android.lib.ad.basic.BannerAdViewHolder
import com.composition.android.lib.ad.basic.BasicAdView
import com.composition.android.lib.ad.util.adLog
import com.composition.android.lib.ad.util.adLogE
import com.composition.android.lib.ad.util.adLogWithFrame

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/11/14
 * description: AppLovinMax横幅广告View
 */
class AppLovinMaxBannerView(context: Context?) : BasicAdView<MaxAdView>(context) {

    private var bannerAdViewHolder: BannerAdViewHolder? = null

    fun setBannerAdViewHolder(adViewHolder: BannerAdViewHolder) {
        this.bannerAdViewHolder = adViewHolder
    }

    override fun adContentView(): MaxAdView? {
        val maxAdView = adResult?.adObject as? MaxAdView
        maxAdView?.setListener(object : MaxAdViewAdListener {
            override fun onAdLoaded(ad: MaxAd?) {


                adLogWithFrame(msg = "AppLovinMax广告-横幅-onAdLoaded")
            }

            override fun onAdDisplayed(ad: MaxAd?) {
                adResult?.adBean?.let { bannerAdViewHolder?.adListener?.onAdShow(it) }
            }

            override fun onAdHidden(ad: MaxAd?) {
                bannerAdViewHolder?.adListener?.onAdClose()
            }

            override fun onAdClicked(ad: MaxAd?) {
                bannerAdViewHolder?.adListener?.onAdClick()
            }

            override fun onAdLoadFailed(adUnitId: String?, error: MaxError?) {

            }

            override fun onAdDisplayFailed(ad: MaxAd?, error: MaxError?) {
                adLogWithFrame(AdManager.TAG, "AppLovinMax广告-横幅-显示失败\ncode:${error?.code}\nmessage:${error?.message}")
                bannerAdViewHolder?.adListener?.onAdShowFail("AppLovinMax广告-横幅-显示失败")
            }

            override fun onAdExpanded(ad: MaxAd?) {

            }

            override fun onAdCollapsed(ad: MaxAd?) {
            }

        })

        return maxAdView
    }

    override fun onResume() {
        (adResult?.adObject as? MaxAdView)?.startAutoRefresh()
    }

    override fun onPause() {
        (adResult?.adObject as? MaxAdView)?.stopAutoRefresh()
    }

    override fun onDestroy() {
        (adResult?.adObject as? MaxAdView)?.also {
            it.stopAutoRefresh()
            it.destroy()
        }
        adResult?.adObject = null
    }
}