package com.cmvr.test.flow.runtime.interceptor;

import com.cmvr.test.flow.runtime.event.FlowExecutionEvent;
import com.cmvr.test.flow.runtime.event.FlowExecutionEventPublisher;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.function.Function;

@Slf4j
@Component
@Order(1)
public class FlowBeforeInterceptor extends AbstractFlowMsgPreInterceptor{

    public FlowBeforeInterceptor(FlowExecutionEventPublisher eventPublisher) {
        super(eventPublisher);
    }

    @Override
    public TaskNodeExecuteResult doIntercept(TaskNodeExecuteMessage message, Function<TaskNodeExecuteMessage, TaskNodeExecuteResult> next) {
        FlowExecutionEvent event = FlowExecutionEvent.builder()
                .eventType(FlowExecutionEvent.EventType.NODE_STARTED)
                .instId(message.getInstId())
                .taskId(message.getTaskId())
                .itemId(message.getItemId())
                .nodeId(message.getNodeId())
                .nodeCount(message.getGraph().allNodeIds().size())
                .nodeName(message.getNodeName())
                .nodeType(message.getNodeType())
                .build();

        eventPublisher.publishEvent(event);
        return next.apply(message);
    }
}
