package com.cmvr.test.flow.runtime.engine.support;

import cn.hutool.core.collection.CollUtil;
import com.cmvr.test.flow.runtime.dispatcher.FlowNodeTypeDispatch;
import com.cmvr.test.flow.runtime.interceptor.FlowMsgPreInterceptor;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.function.Function;

@Component
@RequiredArgsConstructor
public class FlowExecutionChainBuilder {

    /**
     * 构建拦截责任链
     */
    public Function<TaskNodeExecuteMessage, TaskNodeExecuteResult> build(
            List<FlowMsgPreInterceptor> interceptors,
            FlowNodeTypeDispatch dispatchHandler) {

        List<FlowMsgPreInterceptor> reversed = CollUtil.reverseNew(interceptors);
        Function<TaskNodeExecuteMessage, TaskNodeExecuteResult> next = dispatchHandler::dispatch;

        for (FlowMsgPreInterceptor interceptor : reversed) {
            Function<TaskNodeExecuteMessage, TaskNodeExecuteResult> finalNext = next;
            next = msg -> interceptor.intercept(msg, finalNext);
        }
        return next;
    }
}
