package com.gh.gamecenter.gamedetail.accelerator.chain

import android.content.Context
import com.gh.gamecenter.core.provider.IAcceleratorProvider
import com.gh.gamecenter.gamedetail.accelerator.dialog.AcceleratorDialogFragment
import com.gh.gamecenter.gamedetail.accelerator.dialog.AcceleratorDialogFragment.Companion.SPEED_CURRENT_ACCELERATING
import com.gh.gamecenter.gamedetail.accelerator.dialog.AcceleratorReplaceDialogFragment
import com.halo.assistant.accelerator.repository.AcceleratorDataHolder
import com.therouter.TheRouter

class AcceleratorStateInterceptor : AcceleratorValidator.Interceptor {
    override fun intercept(
        context: Context,
        chain: AcceleratorValidator.Chain,
        listener: AcceleratorValidator.ValidateListener?
    ) {
        val request = chain.request
        val iAcceleratorProvider = TheRouter.get(IAcceleratorProvider::class.java)
        val isAccelerating = iAcceleratorProvider?.isCurAccSuccess() ?: false
        if (isAccelerating) {
            val game = request.game
            val isCurrentAccelerating = AcceleratorDataHolder.instance.isCurrentGameAccelerating(game.id)
            if (isCurrentAccelerating) {
                AcceleratorDialogFragment.show(
                    SPEED_CURRENT_ACCELERATING,
                    game.getUniquePackageName() ?: "",
                    game.id,
                    game.name ?: "",
                    request.sourceEntrance,
                    context
                )
            } else {
                AcceleratorReplaceDialogFragment.show(
                    context,
                    game.getUniquePackageName() ?: "",
                    game.id,
                    game.name ?: "",
                    request.sourceEntrance
                ) {
                    if (chain.isValidContext(context)) {
                        listener?.finished(context)
                    }
                }
            }

        } else {
            chain.proceed(context, request, listener)
        }


    }
}