package com.gh.common.chain

class DownloadChainBuilder {

    private val handlers: MutableList<DownloadChainHandler> = ArrayList()

    private var processEndCallback: ((asVGame: Boolean, Any?) -> Unit)? = null

    fun setProcessEndCallback(gameId: String, callback: (asVGame: Boolean, Any?) -> Unit): DownloadChainBuilder {
        processEndCallback = VaPluginDownloadWrapper(gameId = gameId, callback = callback) // 其他需要添加行为的装饰者可以一直包装A(B(C(callback))), 执行顺序 A->B->C->callback
        return this
    }

    fun addHandler(handler: DownloadChainHandler): DownloadChainBuilder {
        handlers.add(handler)
        return this
    }

    fun buildHandlerChain(): DownloadChainHandler? {
        for (i in handlers.indices) {
            handlers[i].processEndCallback = processEndCallback
            if (i + 1 < handlers.size) {
                handlers[i].setNext(handlers[i + 1])
            }
        }
        return if (handlers.isEmpty()) null else handlers[0]
    }
}