package com.composition.android.ad.gromore.beizis

import android.content.Context
import android.view.ViewGroup
import androidx.fragment.app.FragmentActivity
import androidx.lifecycle.lifecycleScope
import com.beizi.fusion.AdListener
import com.beizi.fusion.SplashAd
import com.bytedance.pangle.wrapper.PluginFragmentActivityWrapper
import com.bytedance.sdk.openadsdk.AdSlot
import com.bytedance.sdk.openadsdk.mediation.MediationConstant
import com.bytedance.sdk.openadsdk.mediation.MediationConstant.AdIsReadyStatus
import com.bytedance.sdk.openadsdk.mediation.bridge.custom.splash.MediationCustomSplashLoader
import com.bytedance.sdk.openadsdk.mediation.custom.MediationCustomServiceConfig
import com.composition.android.ad.gromore.util.ThreadUtils
import com.composition.android.lib.ad.util.adLogWithFrame
import com.composition.android.lib.ad.util.getScreenHeight
import com.composition.android.lib.ad.util.getScreenWidth
import kotlinx.coroutines.*
import java.util.concurrent.Callable
import java.util.concurrent.Future
import java.util.concurrent.TimeUnit

/**
 * @author: HuBoWen
 * @date: 2023/4/25
 * @description:
 */
class CustomBeiZiAppOpenRequestImpl : MediationCustomSplashLoader() {

    private var splash: SplashAd? = null

    private var context : Context? = null

    override fun load(context: Context, adSlot: AdSlot?, serviceConfig: MediationCustomServiceConfig?) {

        GlobalScope.launch(Dispatchers.IO) {
            if (context is FragmentActivity) {
                context.lifecycleScope.launch(Dispatchers.Main) {
                    this@CustomBeiZiAppOpenRequestImpl.context = context
                    val activityWrapper = (context as? PluginFragmentActivityWrapper)
                    if (activityWrapper == null) {
                        adLogWithFrame(msgs = arrayOf( "GroMore-开屏-自定义BeiZis,加载取消，context必须为Activity"))
                        callLoadFail(0, "context is not Activity")
                        return@launch
                    }
                    val activity = activityWrapper.originActivity
                    //step3:创建开屏广告请求参数AdSlot,具体参数含义参考文档
                    val splashWidthPx: Int = adSlot?.imgAcceptedWidth ?: getScreenWidth(activity)
                    val screenHeightPx: Int = adSlot?.imgAcceptedHeight ?: getScreenHeight(activity)
                    val slotId = serviceConfig?.adnNetworkSlotId
                    adLogWithFrame(
                        msgs = arrayOf(
                            "加载GroMore自定义广告",
                            "广告商:BeiZis",
                            "广告ID:${slotId}"
                        )
                    )
                    splash = SplashAd(activity, null, slotId, object : AdListener {
                        override fun onAdLoaded() {
                            adLogWithFrame(msgs = arrayOf( "GroMore-开屏-自定义BeiZis,加载成功"))
                            if (biddingType == MediationConstant.AD_TYPE_CLIENT_BIDING) {
                                var epcm = splash?.ecpm?.toDouble()
                                epcm?.apply {
                                    if (this < 0) {
                                        epcm = 0.0
                                    }
                                    callLoadSuccess(epcm!!)
                                }
                            } else {
                                callLoadSuccess()
                            }
                        }

                        override fun onAdShown() {
                            callSplashAdShow()
                        }

                        override fun onAdFailedToLoad(p0: Int) {
                            adLogWithFrame(msgs = arrayOf( "GroMore-开屏-自定义BeiZis,加载失败-ErrorCode:${p0}"))
                            callLoadFail(p0, "BeiZis load Failed ErrorCode:${p0}")
                        }

                        override fun onAdClosed() {
                            callSplashAdDismiss()
                        }

                        override fun onAdTick(p0: Long) {
                        }

                        override fun onAdClicked() {
                            callSplashAdClicked()
                        }
                    }, 5000)
                    splash?.loadAd(splashWidthPx, (screenHeightPx - 100))
                }
            }
        }
    }


    override fun showAd(container: ViewGroup?) {
        ThreadUtils.runOnUIThreadByThreadPool {
            if (splash != null) {
                splash?.show(container)
            }else{
                callSplashAdSkip()
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        context?.let {
            splash?.cancel(it)
        }
    }

    override fun isReadyCondition(): AdIsReadyStatus {
        /**
         * 在子线程中进行广告是否可用的判断
         */
        val future: Future<AdIsReadyStatus> = ThreadUtils.runOnThreadPool(Callable {
            if (splash != null) {
                AdIsReadyStatus.AD_IS_READY
            } else {
                AdIsReadyStatus.AD_IS_NOT_READY
            }
        })
        try {
            val result = future[5000, TimeUnit.MILLISECONDS] //设置500毫秒的总超时，避免线程阻塞
            return result ?: AdIsReadyStatus.AD_IS_NOT_READY
        } catch (e: Exception) {
            e.printStackTrace()
        }
        return AdIsReadyStatus.AD_IS_READY
    }
}