package org.hzhub.workflow.workflow.node.start;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.hzhub.common.core.exception.base.BaseException;
import org.hzhub.workflow.entity.WorkflowComponent;
import org.hzhub.workflow.entity.WorkflowNode;
import org.hzhub.workflow.util.JsonUtil;
import org.hzhub.workflow.workflow.NodeProcessResult;
import org.hzhub.workflow.workflow.WfNodeIODataUtil;
import org.hzhub.workflow.workflow.WfNodeState;
import org.hzhub.workflow.workflow.WfState;
import org.hzhub.workflow.workflow.data.NodeIOData;
import org.hzhub.workflow.workflow.node.AbstractWfNode;

import java.util.List;

import static org.hzhub.workflow.cosntant.AdiConstant.WorkflowConstant.DEFAULT_OUTPUT_PARAM_NAME;
import static org.hzhub.common.chat.enums.ErrorEnum.A_WF_NODE_CONFIG_ERROR;
import static org.hzhub.common.chat.enums.ErrorEnum.A_WF_NODE_CONFIG_NOT_FOUND;

@Slf4j
public class StartNode extends AbstractWfNode {

    public StartNode(WorkflowComponent wfComponent, WorkflowNode nodeDef, WfState wfState, WfNodeState nodeState) {
        super(wfComponent, nodeDef, wfState, nodeState);
    }

    @Override
    public NodeProcessResult onProcess() {
        String objectConfig = node.getNodeConfig();
        if (null == objectConfig) {
            throw new BaseException(A_WF_NODE_CONFIG_NOT_FOUND.getInfo());
        }
        List<NodeIOData> result;
        StartNodeConfig nodeConfigObj = JsonUtil.fromJson(objectConfig, StartNodeConfig.class);
        if (null == nodeConfigObj) {
            log.warn("找不到开始节点的配置");
            throw new BaseException(A_WF_NODE_CONFIG_ERROR.getInfo());
        }
        if (StringUtils.isNotBlank(nodeConfigObj.getPrologue())) {
            result = List.of(NodeIOData.createByText(DEFAULT_OUTPUT_PARAM_NAME, "default", nodeConfigObj.getPrologue()));
        } else {
            result = WfNodeIODataUtil.changeInputsToOutputs(state.getInputs());
        }
        return NodeProcessResult.builder().content(result).build();
    }

}
