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

import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteMessage;
import com.cmvr.test.flow.runtime.message.TaskNodeExecuteResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;

@Slf4j
@Component("GET_CURRENT_OBJECT")
public class FlowGetCurrentObjNodeHandler implements FlowNodeTypeHandler {


    @Override
    public TaskNodeExecuteResult handle(TaskNodeExecuteMessage message) {
        try {
//            JSONObject inputParams = message.getInputParams();
//            JSONArray jsonArray = inputParams.getJSONArray("array");
//
//            List<Integer> iterations = message.getIterations();
//            int last = CollUtil.getLast(iterations) - 1;
            int index = message.getLoopNum() - 1;
            JSONObject output = new JSONObject();
            output.put("index", index);
            JSONArray objects = (JSONArray)message.getLoopArray();
            if (CollUtil.isNotEmpty(objects) && index >= 0) {
                output.put("object", objects.get(index));
            }

            return TaskNodeExecuteResult.success(output);

        } catch (Exception e) {
            log.error("[FLOW][GET_CURRENT_OBJECT] 执行异常", e);
            return TaskNodeExecuteResult.failure(e.getMessage());
        }
    }
}
