package com.gh.common.prioritychain

import com.lightgame.utils.Utils
import java.util.*
import java.util.concurrent.PriorityBlockingQueue

class PriorityChain(private val completeCallback: (() -> Unit)? = null) {

    private val handlerQueue: Queue<PriorityChainHandler> = PriorityBlockingQueue()

    /**
     * 添加 handler 到队列中
     */
    fun addHandler(handler: PriorityChainHandler) {
        handlerQueue.add(handler.also {
            it.setPriorityChain(this)
        })
    }

    /**
     * 启动队列中的 handler
     */
    fun start() {
        handlerQueue.peek()?.let {
            it.injectQueue(handlerQueue)
            it.process()
        }
    }

    /**
     * 恢复队列中的 handler
     */
    fun resume() {
        val handler = handlerQueue.peek()

        if (handler?.getStatus() == PriorityChainHandler.STATUS_HANDLING) {
            Utils.log(PriorityChainHandler.TAG, "${handler.javaClass.simpleName} 处于执行中状态，不用恢复")
        } else {
            handler?.injectQueue(handlerQueue)
            handler?.process()
        }
    }

    /**
     * 队列是否为空
     */
    fun isHandlerQueueEmpty() = handlerQueue.isEmpty()


    fun onHandleComplete() {
        completeCallback?.invoke()
    }

}