package com.gh.common.chain

class ChainBuilder {

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

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

    fun setProcessEndCallback(callback: (Any?) -> Unit): ChainBuilder {
        processEndCallback = callback
        return this
    }

    fun addHandler(handler: ChainHandler): ChainBuilder {
        handlers.add(handler)
        return this
    }

    fun buildHandlerChain(): ChainHandler? {
        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]
    }
}