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

import android.content.Context
import android.os.Parcelable
import androidx.appcompat.app.AppCompatActivity
import com.gh.gamecenter.feature.entity.GameEntity
import com.gh.gamecenter.gamedetail.accelerator.chain.AcceleratorValidator.Request
import kotlinx.parcelize.Parcelize

class AcceleratorValidator {

    interface ValidateListener {

        fun finished(context: Context)
    }

    interface Interceptor {

        fun intercept(context: Context, chain: Chain, listener: ValidateListener?)
    }

    interface Chain {

        val request: Request

        fun proceed(context: Context, request: Request, listener: ValidateListener?)

        fun isValidContext(context: Context) =
            context is AppCompatActivity && !context.isFinishing && !context.isDestroyed
    }

    @Parcelize
    data class Request(
        val game: GameEntity,
        val sourceEntrance: String
    ) : Parcelable

}

class RealAcceleratorInterceptorChain(
    private val interceptors: List<AcceleratorValidator.Interceptor>,
    private val index: Int,
    private val _request: Request
) : AcceleratorValidator.Chain {

    override val request: Request
        get() = _request

    override
    fun proceed(context: Context, request: Request, listener: AcceleratorValidator.ValidateListener?) {
        if (!isValidContext(context)) {
            // 如果 context失效，说明当前页面已销毁，直接中断流程
            return
        }
        if (index >= interceptors.size) {
            // 验证完成
            listener?.finished(context)
            return
        }
        val next = RealAcceleratorInterceptorChain(
            interceptors,
            index + 1,
            _request
        )
        interceptors[index].intercept(context, next, listener)
    }
}


