package com.gh.gamecenter.gamedetail.accelerator

import android.content.Context
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import com.gh.common.util.CheckLoginUtils
import com.gh.common.util.PackageLauncher
import com.gh.gamecenter.R
import com.gh.gamecenter.common.constant.Constants
import com.gh.gamecenter.common.utils.*
import com.gh.gamecenter.core.callback.AccelerateState
import com.gh.gamecenter.core.callback.OnAccelerateListener
import com.gh.gamecenter.core.provider.IAcceleratorProvider
import com.gh.gamecenter.core.utils.SPUtils
import com.gh.gamecenter.databinding.DetailDownloadItemBinding
import com.gh.gamecenter.feature.entity.AcctGameInfo
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.gamedetail.accelerator.chain.AcceleratorClient
import com.gh.gamecenter.gamedetail.accelerator.chain.AcceleratorValidator
import com.gh.gamecenter.gamedetail.accelerator.dialog.AcceleratorDialogFragment
import com.gh.gamecenter.gamedetail.accelerator.dialog.AcceleratorDialogFragment.Companion.SPEED_STOP
import com.gh.gamecenter.gamedetail.accelerator.dialog.AcceleratorZoneDialogFragment
import com.gh.gamecenter.gamedetail.accelerator.dialog.StartingAcceleratorDialogFragment
import com.halo.assistant.accelerator.repository.AcceleratorDataHolder
import com.therouter.TheRouter

class GameDetailAcceleratorUiHelper(private val binding: DetailDownloadItemBinding) {

    private var iAcceleratorProvider = TheRouter.get(IAcceleratorProvider::class.java)

    private var guideView: AcceleratorGuideView? = null

    private lateinit var game: GameEntity

    private var isGuideLayerShowing = false

    private var _last: AcctGameInfo? = null
    private val last: AcctGameInfo?
        get() = _last

    private val hasMultiZone: Boolean
        get() = game.serviceArea.size > 1

    private val isVip: Boolean
        get() = AcceleratorDataHolder.instance.isVip

    val isNewUser: Boolean
        get() = AcceleratorDataHolder.instance.isNewUser

    private val isInit: Boolean
        get() = ::game.isInitialized

    val context: Context
        get() = binding.root.context

    private var hasAnyAcctRecord = false

    private var showDualDownloadButton: Boolean = false

    private val accelerationListener = object : OnAccelerateListener {
        override fun onStateChanged(state: AccelerateState) {
            when (state) {
                is AccelerateState.Success -> {
                    updateSpeedUi()

                }

                is AccelerateState.Normal -> {
                    updateSpeedUi()
                }

                else -> Unit
            }
        }

        override fun onProgress(progress: Int, curGamePkgName: String?, curGameZoneFlag: String?) = Unit

    }

    private val onDataHolderListener = object : AcceleratorDataHolder.OnDataHolderListener {
        override fun onVipStateChanged() {
            showFreeTag()
        }
    }

    fun initUi(game: GameEntity, context: Context) {
        this.game = game
        iAcceleratorProvider?.bindAccRelatedListener(game.getUniquePackageName() ?: "", accelerationListener)
        AcceleratorDataHolder.instance.addListener(onDataHolderListener)

        binding.vSpeedContent.setOnClickListener {
            startAccelerating(context, game, false)
        }
        binding.vMoreZone.setOnClickListener {
            showZoneList(context, game)
        }

        binding.tvStopSpeed.setOnClickListener {
            SensorsBridge.trackNetworkAccelerationOtherButtonClick(
                game.getUniquePackageName() ?: "",
                game.id,
                game.name ?: "",
                AcceleratorDataHolder.instance.memberType,
                BUTTON_NAME_STOP_ACCELERATOR,
                SOURCE_ENTRANCE_GAME_DETAIL
            )

            AcceleratorDialogFragment.show(
                SPEED_STOP, game.getUniquePackageName() ?: "", game.id, game.name ?: "",
                SOURCE_ENTRANCE_GAME_DETAIL, context
            )
        }

        binding.tvEnterGame.setOnClickListener {
            SensorsBridge.trackNetworkAccelerationOtherButtonClick(
                game.getUniquePackageName() ?: "",
                game.id,
                game.name ?: "",
                AcceleratorDataHolder.instance.memberType,
                BUTTON_NAME_ENTER_GAME,
                SOURCE_ENTRANCE_GAME_DETAIL
            )
            PackageLauncher.launchApp(context, game, game.getUniquePackageName())
        }

        updateSpeedUi()
    }

    fun updateSpeedUi() {
        if (!isInit || !showSpeedUi) {
            return
        }

        val isCurrentGameAccelerating = AcceleratorDataHolder.instance.isCurrentGameAccelerating(game.id)

        if (!showDualDownloadButton) {
            when {
                isCurrentGameAccelerating -> {// 如果当前游戏正处于加速状态，则需要隐藏当前下载按钮
                    binding.detailProgressbar.goneIf(true)
                }

                binding.detailProgressbar.text == "更新" -> { // 游戏没有处于加速状态，如果 下载按钮为 “更新” 状态，则需要显示出来
                    binding.detailProgressbar.setBackgroundResource(com.gh.gamecenter.common.R.drawable.bg_common_button_light_fill_blue)
                    binding.detailProgressbar.setTextColor(com.gh.gamecenter.common.R.color.text_theme.toColor(context))
                    binding.detailProgressbar.goneIf(false)
                }
            }
        }

        binding.clSpeed.goneIf(isCurrentGameAccelerating)
        binding.gAccelerating.goneIf(!isCurrentGameAccelerating)
        binding.gMoreZone.goneIf(!hasMultiZone)
        showFreeTag()
        binding.tvSpeed.text = if (hasMultiZone) {
            last?.zoneName
        } else {
            null
        } ?: R.string.network_acceleration.toResString()
    }

    fun checkIfShowSpeedUi(show: Boolean, showDualDownloadButton: Boolean) {
        this.showDualDownloadButton = showDualDownloadButton
        if (!isInit) {
            return
        }
        showSpeedUi = show
        binding.clSpeedContainer.goneIf(!showSpeedUi) {
            // 是否需要展示弹窗
            showGuideLayerIfNeed()
            updateSpeedUi()
        }
    }

    private fun showFreeTag() {
        binding.ivFreeVipTag.visibleIf(
            showSpeedUi && last == null && !isGuideLayerShowing &&
                    (!CheckLoginUtils.isLogin() || isNewUser)
        )
    }

    /**
     * 需要同时满足这四个条件，才需要判断是否需要展示弹窗
     */
    var isButtonSizeDetermined = false  // 底部下载按钮尺寸是否已确定
    private var isLastLoaded = false    // 本地存在区服记录（用户点击过选择区服/启动加速）
    private var hasAnyAcctRecordLoaded = false  // 已获取：是否存在加速成功的游戏记录
    private var showSpeedUi = false     // 显示加速器ui
    fun showGuideLayerIfNeed() {
        if (isButtonSizeDetermined && hasAnyAcctRecordLoaded && isLastLoaded && showSpeedUi) {
            if (shouldShowGuideLayer()) {
                isGuideLayerShowing = true
                showGuideLayer(context)
            }
            showFreeTag()
        }

    }

    private fun shouldShowGuideLayer() =
        !SPUtils.getBoolean(Constants.SP_HAS_SHOW_ACCELERATION_GUIDE_LAYER) &&
                !hasAnyAcctRecord &&
                last == null &&
                !isGuideLayerShowing

    private fun showGuideLayer(context: Context) {
        binding.root.post {
            val uiListener = object : OnAcceleratorListener {
                override fun onStartAccelerator() {
                    startAccelerating(context, game, true)
                }

                override fun onGuideLayerDismiss() {
                    isGuideLayerShowing = false
                    showFreeTag()
                }

            }
            SPUtils.setBoolean(Constants.SP_HAS_SHOW_ACCELERATION_GUIDE_LAYER, true)
            if (guideView == null) {
                guideView = AcceleratorGuideView(context).apply {
                    setDismissListener(uiListener::onGuideLayerDismiss)
                }
            }
            (guideView?.parent as? ViewGroup)?.removeView(guideView)
            if (context is AppCompatActivity) {
                SensorsBridge.trackNetworkAccelerationGuidanceDiagramShow(
                    game.getUniquePackageName() ?: "",
                    game.id,
                    game.name ?: ""
                )
                guideView?.show(binding.clSpeed, context, uiListener::onStartAccelerator)
            }
        }

    }

    fun onBack(): Boolean {
        val isShowing = guideView?.isShowing ?: false
        if (isShowing) {
            guideView?.dismiss()
            return true
        } else {
            return false
        }
    }

    private fun startAccelerating(context: Context, game: GameEntity, isShowing: Boolean) {
        if (isInvalidClick()) {
            return
        }

        val lastAcctGameInfo = last

        val memberType = AcceleratorDataHolder.instance.memberType
        val districtServer = when {
            hasMultiZone && lastAcctGameInfo != null -> lastAcctGameInfo.zoneName
            hasMultiZone -> DISTRICT_SERVER_EMPTY
            else -> DISTRICT_SERVER_HAVA
        }
        SensorsBridge.trackNetworkAccelerationButtonClick(
            game.getUniquePackageName() ?: "",
            game.id,
            game.name ?: "",
            memberType,
            districtServer,
            if (isShowing) SCENE_TYPE_HAVE_GUIDE_LAYER else SCENE_TYPE_NO_GUIDE_LAYER,
            SOURCE_ENTRANCE_GAME_DETAIL
        )

        when {
            lastAcctGameInfo != null ->
                doStartAccelerating(context, game, lastAcctGameInfo.zoneInfo)

            hasMultiZone -> context.ifLogin("[网络加速]") {
                AcceleratorZoneDialogFragment.show(
                    context, last?.zoneInfo?.id, game.serviceArea, game,
                    SOURCE_ENTRANCE_GAME_DETAIL
                )
            }

            else -> {
                val gameInfo = game.serviceArea.firstOrNull() ?: AcctGameInfo.ZoneInfo(0)
                doStartAccelerating(context, game, gameInfo)
            }
        }

    }

    private fun showZoneList(context: Context, game: GameEntity) {
        if (isInvalidClick()) {
            return
        }
        context.ifLogin("[网络加速]") {
            AcceleratorZoneDialogFragment.show(
                context, last?.zoneInfo?.id, game.serviceArea, game,
                SOURCE_ENTRANCE_GAME_DETAIL
            )
        }

    }

    private var clickTime = 0L

    private fun doStartAccelerating(context: Context, game: GameEntity, zoneInfo: AcctGameInfo.ZoneInfo) {

        val request = AcceleratorValidator.Request(game, SOURCE_ENTRANCE_GAME_DETAIL)
        AcceleratorClient.newInstance()
            .execute(context, request, object : AcceleratorValidator.ValidateListener {
                override fun finished(context: Context) {
                    StartingAcceleratorDialogFragment.show(
                        context, zoneInfo, game, true, hasMultiZone,
                        SOURCE_ENTRANCE_GAME_DETAIL,
                    )
                }
            })
    }

    fun setCurrentAcctGameInfo(acctGameInfo: AcctGameInfo?) {
        isLastLoaded = true
        if (last?.zoneInfo?.id != acctGameInfo?.zoneInfo?.id) {
            _last = acctGameInfo
            updateSpeedUi()
        }
        showGuideLayerIfNeed()
    }

    fun setHasAnyAcctRecord(hasAnyAcctRecord: Boolean) {
        hasAnyAcctRecordLoaded = true
        this.hasAnyAcctRecord = hasAnyAcctRecord
        showGuideLayerIfNeed()
    }

    private fun isInvalidClick(): Boolean {
        // 300ms内只能调用一次
        val currentTime = System.currentTimeMillis()
        val difTime = currentTime - clickTime
        if (difTime <= CLICK_DURATION) {
            return true
        }
        clickTime = currentTime
        return false
    }

    fun clear() {
        iAcceleratorProvider?.unBindAccRelatedListener(accelerationListener)
        AcceleratorDataHolder.instance.removeListener(onDataHolderListener)
        guideView?.dismiss()
    }


    companion object {

        private const val CLICK_DURATION = 300


        const val DISTRICT_SERVER_EMPTY = "空"
        const val DISTRICT_SERVER_HAVA = "有"
        private const val SCENE_TYPE_HAVE_GUIDE_LAYER = "有引导图"
        const val SCENE_TYPE_NO_GUIDE_LAYER = "无引导图"
        const val SOURCE_ENTRANCE_GAME_DETAIL = "游戏详情页"
        const val SOURCE_ENTRANCE_MY_ASSETS = "我的资产"
        const val SOURCE_ENTRANCE_SEARCH = "搜索页"
        const val SOURCE_ENTRANCE_RECENTLY_PLAYED = "最近在玩"
        const val BUTTON_NAME_ENTER_GAME = "进入游戏"
        const val BUTTON_NAME_STOP_ACCELERATOR = "停止加速"

    }

    interface OnAcceleratorListener {

        fun onStartAccelerator()

        fun onGuideLayerDismiss()
    }
}