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

import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import com.cmvr.test.util.NashornJsExecutor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;


@Slf4j
@Component("CODE")
@RequiredArgsConstructor
public class FlowCodeNodeHandler implements FlowNodeTypeHandler {

    private final NashornJsExecutor nashornJsExecutor;

    @Override
    public TaskNodeExecuteResult handle(TaskNodeExecuteMessage message) {
        String nodeId = message.getNodeId();
        JSONObject inputParams = message.getInputParams();
        String code = inputParams.getString("code");
        inputParams.remove("code");
        log.info("code 节点 {} 开始执行", nodeId);
        Object execute = nashornJsExecutor.execute(code, inputParams);

        log.info("code 节点 {} 执行完成", nodeId);
        return TaskNodeExecuteResult.success(JSONObject.of("result", execute));
    }
}
