package com.composition.android.ad.gromore.load

import android.app.Activity
import android.content.Context
import android.view.View
import android.view.ViewGroup
import com.bytedance.msdk.api.AdError
import com.bytedance.msdk.api.format.TTNativeAdView
import com.bytedance.msdk.api.reward.RewardItem
import com.bytedance.msdk.api.v2.ad.banner.GMBannerAd
import com.bytedance.msdk.api.v2.ad.interstitialFull.GMInterstitialFullAd
import com.bytedance.msdk.api.v2.ad.interstitialFull.GMInterstitialFullAdListener
import com.bytedance.msdk.api.v2.ad.nativeAd.GMNativeAd
import com.bytedance.msdk.api.v2.ad.nativeAd.GMUnifiedNativeAd
import com.bytedance.msdk.api.v2.ad.reward.GMRewardAd
import com.bytedance.msdk.api.v2.ad.reward.GMRewardedAdListener
import com.bytedance.msdk.api.v2.ad.splash.GMSplashAd
import com.bytedance.msdk.api.v2.ad.splash.GMSplashAdListener
import com.composition.android.ad.gromore.load.request.*
import com.composition.android.ad.gromore.load.view.GMBannerView
import com.composition.android.ad.gromore.load.view.GMNativeTemplateAdView
import com.composition.android.lib.ad.AdManager
import com.composition.android.lib.ad.basic.*
import com.composition.android.lib.ad.bean.AdUnitBean
import com.composition.android.lib.ad.interfaces.AdListener
import com.composition.android.lib.ad.interfaces.AdLoader
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/9/15
 * description:GroMore广告加载类
 */
class GroMoreAdLoader : AdLoader {

    override val advertisers: Advertisers
        get() = Advertisers.GroMore

    /**
     * 加载广告，根据广告类型加载对应格式广告
     * @param adUnitBean 广告配置数据类
     */
    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {
        val adRequest = when (adUnitBean.getAdType()) {
            AdType.BANNER -> GMBannerRequestImpl()
            AdType.NATIVE_TEMPLATE -> GMNativeTemplateRequestImpl()
            AdType.INTERSTITIAL, AdType.REWARDED_INTERSTITIAL -> GMInterstitialRequestImpl()
            AdType.REWARDED_VIDEO -> GMRewardRequestImpl()
            AdType.APP_OPEN -> GMAppOpenRequestImpl()
            else -> {
                adLogE(tag = AdManager.TAG, msg = "GroMore广告-不支持加载-${adUnitBean.adType}-类型广告")
                null
            }
        }
        return loadByStrategy(context, adUnitBean, adRequest)
    }

    override fun getBannerView(context: Context, adResult: AdResult.Success, viewHolder: BannerAdViewHolder): BasicAdView<*>? {
        return if (adResult.adObject != null) {
            GMBannerView(context).apply {
                setBannerViewHolder(viewHolder)
                render(adResult)
                AdManager.instance.globalListener?.invoke(adResult.adBean)
            }
        } else {
            null
        }
    }

    override fun getNativeAdView(context: Context, adResult: AdResult.Success, viewHolder: NativeAdViewHolder): View? {
        return if (adResult.adObject != null){
            when(adResult.adBean.getAdType()){
                AdType.NATIVE_TEMPLATE ->{
                    GMNativeTemplateAdView(context).apply {
                        setViewHolder(viewHolder)
                        render(adResult)
                        AdManager.instance.globalListener?.invoke(adResult.adBean)
                    }
                }
                else->null
            }
        }else{
            null
        }
    }



    override fun populateNativeAdView(context: Context, adResult: AdResult.Success, viewHolder: NativeAdViewHolder, advertisersContainerView: ViewGroup) {
        if (advertisersContainerView is TTNativeAdView) {
            val gmNativeAd = adResult?.adObject as? GMNativeAd
            advertisersContainerView.removeAllViews()
            advertisersContainerView.addView(gmNativeAd?.expressView)
            GMNativeTemplateAdView.populateNativeAdView(context, adResult, viewHolder, advertisersContainerView)
        } else {
            adLogE(AdManager.TAG, "GroMore广告-原生模板-填充失败， adRootView错误，当前类型为${advertisersContainerView.javaClass.simpleName},需要为${TTNativeAdView::class.java.simpleName}")
        }
    }

    override fun showInterstitialAd(activity: Activity, adResult: AdResult.Success, adListener: AdListener) {
        if (adResult.adObject is GMInterstitialFullAd) {
            val mInterstitialFullAd = adResult.adObject as GMInterstitialFullAd
            mInterstitialFullAd.setAdInterstitialFullListener(object : GMInterstitialFullAdListener {
                override fun onInterstitialFullShow() {
                    adLogWithFrame(msg = "GorMore广告-插屏-展示")
                    adListener.onAdShow(adResult.adBean)
                    AdManager.instance.globalListener?.invoke(adResult.adBean)
                }

                override fun onInterstitialFullShowFail(p0: AdError) {
                    adLogWithFrame(msg = "GorMore广告-插屏-展示失败")
                    adListener.onAdShowFail("GorMore广告-插屏-展示失败\n${p0.message}")
                }

                override fun onInterstitialFullClick() {
                    adLogWithFrame(msg = "GorMore广告-插屏-点击")
                    adListener.onAdClick()
                }

                override fun onInterstitialFullClosed() {
                    adLogWithFrame(msg = "GorMore广告-插屏-关闭")
                    adListener.onAdClose()
                }

                override fun onVideoComplete() {
                }

                override fun onVideoError() {
                }

                override fun onSkippedVideo() {
                    adLogWithFrame(msg = "GorMore广告-插屏-跳过")
                    adListener.onAdSkip()
                }

                override fun onAdOpened() {
                }

                override fun onAdLeftApplication() {
                }

                override fun onRewardVerify(p0: RewardItem) {
                    adLogWithFrame(msg = "GorMore广告-插屏-获取奖励")
                    adListener.onAdRewarded()
                }

            })
            mInterstitialFullAd.showAd(activity)

        } else {
            adLogWithFrame(msg = "GorMore广告-插屏-展示失败：类型错误，adObject类型错误或为空:${adResult.adObject?.javaClass?.simpleName}")
            adListener.onAdShowFail("GorMore广告-插屏-加载失败：类型错误，adObject类型错误或为空:${adResult.adObject?.javaClass?.simpleName}")
        }
    }

    override fun showRewardedAd(activity: Activity, adResult: AdResult.Success, adListener: AdListener) {
        if (adResult.adObject is GMRewardAd) {
            val gmRewardAd = adResult.adObject as GMRewardAd
            gmRewardAd.setRewardAdListener(object : GMRewardedAdListener {
                override fun onRewardedAdShow() {
                    adLogWithFrame(msg = "GroMore广告-激励视频-展示")
                    adListener.onAdShow(adResult.adBean)
                    AdManager.instance.globalListener?.invoke(adResult.adBean)
                }

                override fun onRewardedAdShowFail(p0: AdError) {
                    adLogWithFrame(msg = "GroMore广告-激励视频-展示失败\n${p0.message}")
                    adListener.onAdShowFail("GroMore广告-激励视频-展示失败\n${p0.message}")
                }

                override fun onRewardClick() {
                    adLogWithFrame(msg = "GroMore广告-激励视频-点击")
                    adListener.onAdClick()
                }

                override fun onRewardedAdClosed() {
                    adLogWithFrame(msg = "GroMore广告-激励视频-关闭")
                    adListener.onAdClose()
                }

                override fun onVideoComplete() {
                }

                override fun onVideoError() {
                }

                override fun onRewardVerify(p0: RewardItem) {
                    adLogWithFrame(msg = "GroMore广告-激励视频-获取奖励")
                    adListener.onAdRewarded()
                }

                override fun onSkippedVideo() {
                    adLogWithFrame(msg = "GroMore广告-激励视频-跳过")
                    adListener.onAdSkip()
                }
            })

            if (gmRewardAd.isReady) {
                gmRewardAd.showRewardAd(activity)
            } else {
                adListener.onAdShowFail("GroMore广告-激励视频-实例还未准备完成，显示失败")
            }
        } else {
            adLogWithFrame(msg = "GorMore广告-激励视频-展示失败：类型错误，adObject类型错误或为空:${adResult.adObject?.javaClass?.simpleName}")
            adListener.onAdShowFail("GorMore广告-激励视频-加载失败：类型错误，adObject类型错误或为空:${adResult.adObject?.javaClass?.simpleName}")
        }

    }

    override fun showRewardedInterstitialAd(activity: Activity, adResult: AdResult.Success, adListener: AdListener) {
        adLogWithFrame(msg = "GorMore广告-激励插屏-展示失败：不支持激励插屏广告")
        adListener.onAdShowFail("GorMore广告-激励插屏-展示失败：不支持激励插屏广告")
    }

    override fun showSplashAd(activity: Activity, splashViewGroup: ViewGroup?, adResult: AdResult.Success, adListener: AdListener) {
        if (adResult.adObject is GMSplashAd) {
            val gmAppOpenAd = adResult.adObject as GMSplashAd
            if (gmAppOpenAd.isReady) {
                gmAppOpenAd.setAdSplashListener(object : GMSplashAdListener {
                    override fun onAdClicked() {
                        adLogWithFrame(msg = "GroMore广告-开屏-点击")
                        adListener.onAdClick()
                    }

                    override fun onAdShow() {
                        adLogWithFrame(msg = "GroMore广告-开屏-展示")
                        adListener.onAdShow(adResult.adBean)
                        AdManager.instance.globalListener?.invoke(adResult.adBean)
                    }

                    override fun onAdShowFail(p0: AdError) {
                        adLogWithFrame(msg = "GroMore广告-开屏-展示失败\n${p0.message}")
                        adListener.onAdShowFail("GroMore广告-开屏-展示失败\n${p0.message}")
                    }

                    override fun onAdSkip() {
                        adLogWithFrame(msg = "GroMore广告-开屏-跳过")
                        adListener.onAdSkip()
                        gmAppOpenAd.destroy()
                        adResult.adObject = null
                    }

                    override fun onAdDismiss() {
                        adLogWithFrame(msg = "GroMore广告-开屏-关闭")
                        adListener.onAdClose()
                        gmAppOpenAd.destroy()
                        adResult.adObject = null
                    }
                })
                gmAppOpenAd.showAd(splashViewGroup)
            }
        } else {
            adLogWithFrame(msg = "GorMore广告-开屏-展示失败：类型错误，adObject类型错误或为空:${adResult.adObject?.javaClass?.simpleName}")
            adListener.onAdShowFail("GorMore广告-激励视频-加载失败：类型错误，adObject类型错误或为空:${adResult.adObject?.javaClass?.simpleName}")
        }
    }

    override fun showFullScreenAd(activity: Activity, adResult: AdResult.Success, adListener: AdListener) {
        when (adResult.adBean.getAdType()) {
            AdType.INTERSTITIAL -> showInterstitialAd(activity, adResult, adListener)
            AdType.REWARDED_VIDEO -> showRewardedAd(activity, adResult, adListener)
            else -> {
                adLogWithFrame(msg = "GroMore广告-全屏-无对应广告类型的广告进行展示 AdType:${adResult.adBean.adType}")
                adListener.onAdShowFail("GroMore广告-全屏-无对应广告类型的广告进行展示 AdType:${adResult.adBean.adType}")
            }
        }
    }

    override fun destroyAd(adResult: AdResult) {
        try {
            if (adResult is AdResult.Success) {
                when (val ad = adResult.adObject) {
                    is GMBannerAd -> ad.destroy()
                    is GMUnifiedNativeAd -> ad.destroy()
                    else -> {}
                }
                adResult.adObject = null
            }
            adLogWithFrame(msg = "GroMore广告-销毁广告对象完成")
        }catch (e : Exception){

        }
    }
}