package com.huigou.explorer.converters.bpmn;

import com.alibaba.fastjson.JSONArray;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGraphModel;
import org.activiti.bpmn.model.BpmnModel;
import org.activiti.bpmn.model.Process;
import org.apache.commons.lang3.StringUtils;

import java.util.Optional;

/**
 * @author yonghuan
 */
public class ProcessConverter implements ElementConverter {

    private ActivitiListenerParser activitiListenerParser;

    public void setActivitiListenerParser(ActivitiListenerParser activitiListenerParser) {
        this.activitiListenerParser = activitiListenerParser;
    }

    @Override
    public boolean supports(Object mxElement) {
        return mxElement instanceof mxGraphModel;
    }

    @Override
    public void convert(BpmnModel bpmnModel, mxGraphModel graphModel, Object mxElement) {
        mxGraphModel model = (mxGraphModel) mxElement;
        mxCell rootCell = (mxCell) model.getRoot();
        Process process = new Process();
        process.setId(rootCell.getAttribute("code"));
        process.setName(rootCell.getAttribute("label"));
        Optional.ofNullable(rootCell.getAttribute("executionListeners"))
                .filter(StringUtils::isNotBlank)
                .map(JSONArray::parseArray)
                .map(activitiListenerParser::parse)
                .ifPresent(executionListeners -> process.setExecutionListeners(executionListeners));
        bpmnModel.addProcess(process);
    }
}
