package com.composition.android.ad.csj.load

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import com.bytedance.sdk.openadsdk.*
import com.composition.android.ad.csj.load.request.*
import com.composition.android.ad.csj.load.view.CSJBannerView
import com.composition.android.ad.csj.load.view.CSJNativeAdView
import com.composition.android.ad.csj.load.view.CSJNativeTemplateAdView
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
import com.composition.android.lib.ad.util.parentRemove

/**
 * @classname:
 * @author: LiuXiaoLong
 * @date: 2022/9/13
 * description: 穿山甲广告加载类
 */
class CSJAdLoader : AdLoader {


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

    override suspend fun load(context: Context, adUnitBean: AdUnitBean): AdResult {
        if (adUnitBean.isAvailable().not()) {
            return AdResult.Fail(adUnitBean, msg = "AdUnitBean无效")
        }
        //获取到具体的广告格式加载类
        val adFormatRequestImpl =
            when (adUnitBean.getAdType()) {
                AdType.REWARDED_VIDEO -> CSJRewardRequestImpl()
                AdType.INTERSTITIAL -> CSJInterstitialRequestImpl()
                AdType.APP_OPEN -> CSJAppOpenRequestImpl()
                AdType.BANNER -> CSJBannerRequestImpl()
                AdType.NATIVE -> CSJNativeRequestImpl()
                AdType.NATIVE_TEMPLATE -> CSJNativeTemplateRequestImpl()
                else -> null
            }
        return loadByStrategy(context, adUnitBean, adFormatRequestImpl)
    }

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

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


    override fun populateNativeAdView(context: Context, adResult: AdResult.Success, viewHolder: NativeAdViewHolder, advertisersContainerView: ViewGroup) {
        AdManager.instance.globalListener?.invoke(adResult.adBean)
        when (adResult.adBean.getAdType()) {
            AdType.NATIVE -> {
                CSJNativeAdView.populateNativeAdView(context = context, adResult, viewHolder, advertisersContainerView)
            }
            AdType.NATIVE_TEMPLATE -> {
                val ttNativeExpressAd = adResult.adObject as TTNativeExpressAd
                advertisersContainerView.removeAllViews()
                val expressAdView = ttNativeExpressAd.expressAdView
                expressAdView.parentRemove()
                advertisersContainerView.addView(expressAdView)
                CSJNativeTemplateAdView.populateNativeTemplateAdView(context, adResult, viewHolder)
            }
            else->{
                adLogE(tag = AdManager.TAG, msg = "穿山甲广告-填充原生，adType类型错误，不支持")
            }
        }

    }

    override fun showInterstitialAd(activity: Activity, adResult: AdResult.Success, adListener: AdListener) {
        if (adResult.adObject is TTFullScreenVideoAd) {
            val ttFullScreenVideoAd = adResult.adObject as TTFullScreenVideoAd
            ttFullScreenVideoAd.setFullScreenVideoAdInteractionListener(object : TTFullScreenVideoAd.FullScreenVideoAdInteractionListener {
                override fun onAdShow() {
                    adLogWithFrame(msg = "穿山甲广告-插屏-展示")
                    adListener.onAdShow(adResult.adBean)
                    AdManager.instance.globalListener?.invoke(adResult.adBean)
                }

                override fun onAdVideoBarClick() {
                    adLogWithFrame(msg = "穿山甲广告-插屏-点击")
                    adListener.onAdClick()
                }

                override fun onAdClose() {
                    adLogWithFrame(msg = "穿山甲广告-插屏-关闭")
                    adListener.onAdClose()
                    destroyAd(adResult)
                }

                override fun onVideoComplete() {

                }

                override fun onSkippedVideo() {
                    adLogWithFrame(msg = "穿山甲广告-插屏-视频跳过")
                    adListener.onAdSkip()
                }

            })
            ttFullScreenVideoAd.showFullScreenVideoAd(activity, TTAdConstant.RitScenes.CUSTOMIZE_SCENES, null)
        } else {
            adLogWithFrame(
                msg = "穿山甲广告-插屏-错误-类型错误，当前为:${adResult.adObject?.javaClass?.simpleName}, 应该为:TTNativeExpressAd"
            )
            adListener.onAdShowFail("类型错误，当前为:${adResult.adObject?.javaClass?.simpleName}, 应该为:TTNativeExpressAd")
        }
    }

    override fun showRewardedAd(activity: Activity, adResult: AdResult.Success, adListener: AdListener) {

        if (adResult.adObject is TTRewardVideoAd) {
            val ttRewardVideoAd = adResult.adObject as TTRewardVideoAd


            ttRewardVideoAd.setRewardAdInteractionListener(object : TTRewardVideoAd.RewardAdInteractionListener {
                override fun onAdShow() {
                    adLogWithFrame(msg = "穿山甲广告-激励视频-展示")
                    adListener.onAdShow(adResult.adBean)
                    AdManager.instance.globalListener?.invoke(adResult.adBean)
                }

                override fun onAdVideoBarClick() {
                    adLogWithFrame(msg = "穿山甲广告-激励视频-点击")
                    adListener.onAdClick()
                }

                override fun onAdClose() {
                    adLogWithFrame(msg = "穿山甲广告-激励视频-关闭")
                    adListener.onAdClose()
                    destroyAd(adResult)
                }

                override fun onVideoComplete() {

                }

                override fun onVideoError() {
                    adLogWithFrame(msg = "穿山甲广告-激励视频-视频异常")
                }

                override fun onRewardVerify(p0: Boolean, p1: Int, p2: String?, p3: Int, p4: String?) {
                    adLogWithFrame(msg = "穿山甲广告-激励视频-获取奖励")
                    adListener.onAdRewarded()
                }

                override fun onRewardArrived(p0: Boolean, p1: Int, p2: Bundle?) {

                }

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

            })

            ttRewardVideoAd.showRewardVideoAd(activity)

        } else {
            adLogWithFrame(
                msg = "穿山甲广告-激励视频-异常-类型错误，当前类型为:${adResult.adObject?.javaClass?.simpleName}, 应为：TTRewardVideoAd"
            )

            adListener.onAdShowFail("类型错误，当前类型为:${adResult.adObject?.javaClass?.simpleName}, 应为：TTRewardVideoAd")
        }


    }

    override fun showRewardedInterstitialAd(activity: Activity, adResult: AdResult.Success, adListener: AdListener) {
        adLogWithFrame(msg = "穿山甲广告-激励插屏-不支持的广告类型")
        adListener.onAdShowFail("穿山甲广告不支持激励插屏广告，请使用激励视频广告")
    }

    override fun showSplashAd(activity: Activity, splashViewGroup: ViewGroup?, adResult: AdResult.Success, adListener: AdListener) {
        if (adResult.adObject is TTSplashAd) {
            val ttSplashAd = adResult.adObject as TTSplashAd
            ttSplashAd.setSplashInteractionListener(object : TTSplashAd.AdInteractionListener {
                override fun onAdClicked(p0: View?, p1: Int) {
                    adLogWithFrame(msg = "穿山甲广告-开屏-点击")
                    adListener.onAdClick()
                }

                override fun onAdShow(p0: View?, p1: Int) {
                    adLogWithFrame(msg = "穿山甲广告-开屏-展示")
                    adListener.onAdShow(adResult.adBean)
                    AdManager.instance.globalListener?.invoke(adResult.adBean)
                }

                override fun onAdSkip() {
                    adLogWithFrame(msg = "穿山甲广告-开屏-跳过")
                    adListener.onAdSkip()
                    destroyAd(adResult)

                }

                override fun onAdTimeOver() {
                    adLogWithFrame(msg = "穿山甲广告-开屏-超时")
                    adListener.onTimeOver()
                }
            })
            splashViewGroup?.removeAllViews()
            splashViewGroup?.addView(ttSplashAd.splashView)
        } else {
            adLogWithFrame(msg = "穿山甲广告-开屏-异常-类型错误，当前类型为:${adResult.adObject?.javaClass?.simpleName}, 应为：TTRewardVideoAd")
            adListener.onAdShowFail("类型错误，当前类型为:${adResult.adObject?.javaClass?.simpleName}, 应为：TTRewardVideoAd")
        }
    }

    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 = "穿山甲广告-全屏-不支持的广告类型:${adResult.adBean.adType}")
                adListener.onAdShowFail("穿山甲广告-全屏-不支持的广告类型:${adResult.adBean.adType}")
            }
        }
    }

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

        }
    }
}