package com.huigou.explorer.converters.bpmn;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.huigou.explorer.Shape;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGraphModel;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.CallActivity;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.IOParameter;

import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Collectors;

/**
 * @author yonghuan
 */
public class CallActivityConverter extends AbstractElementConverter implements ElementConverter {

    public CallActivityConverter() {
        super(Collections.singletonList(Shape.CALL_ACTIVITY));
    }

    @Override
    protected FlowElement convertInternal(BpmnModel bpmnModel, mxGraphModel graphModel, mxCell cell) {
        CallActivity callActivity = new CallActivity();
        callActivity.setCalledElement(cell.getAttribute("calledElement"));
        parseParameter(cell, "inParameters", callActivity::setInParameters);
        parseParameter(cell, "outParameters", callActivity::setOutParameters);
        return callActivity;
    }

    private void parseParameter(mxCell cell, String attrName, Consumer<List<IOParameter>> consumer) {
        Optional.ofNullable(cell.getAttribute(attrName))
                .filter(Objects::nonNull)
                .map(JSONArray::parseArray)
                .map(parameters -> parameters.stream()
                        .map(JSONObject.class::cast)
                        .map(json -> json.toJavaObject(IOParameter.class))
                        .collect(Collectors.toList())
                )
                .ifPresent(consumer);
    }
}
