package cn.stylefeng.workflow.instance.core.actions.gateway;


import cn.hutool.core.util.ObjectUtil;
import cn.stylefeng.workflow.api.entity.design.Node;
import cn.stylefeng.workflow.api.entity.instance.RuntimeNode;
import cn.stylefeng.workflow.api.enums.NodeTypeEnum;
import cn.stylefeng.workflow.api.pojo.InstanceContext;
import cn.stylefeng.workflow.instance.api.node.NodeAction;
import cn.stylefeng.workflow.instance.api.pojo.NodeActionResult;
import cn.stylefeng.workflow.log.api.WorkflowLogApi;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
@Slf4j
public class ParallelGatewayNodeAction extends NodeAction {

    @Resource
    private WorkflowLogApi workflowLogApi;

    @Override
    public NodeTypeEnum getNodeType() {
        return NodeTypeEnum.PARALLEL_GATEWAY;
    }

    @Override
    public NodeActionResult doAction(Node nodeInfo, InstanceContext instanceContext) {

        RuntimeNode runtimeNode = super.createAndSaveRuntimeNode(nodeInfo, instanceContext);

        List<Node> nextNodeList = super.calcNextNodeList(nodeInfo, instanceContext);

        if (ObjectUtil.isEmpty(nextNodeList)) {
            workflowLogApi.logSuccess(instanceContext, nodeInfo.getNodeId(), "并行网关接下来没有分支可执行，终止流程");
            return new NodeActionResult(runtimeNode, null, instanceContext.getInstanceVariable());
        }

        else {
            return new NodeActionResult(runtimeNode, nextNodeList, instanceContext.getInstanceVariable());
        }
    }

}