package com.huigou.explorer.converters.bpmn;

import com.huigou.explorer.util.MxCellUtils;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGraphModel;
import org.activiti.bpmn.model.*;

import java.util.Arrays;
import java.util.Optional;

import static com.huigou.explorer.Shape.*;

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

    public EndEventConverter() {
        super(Arrays.asList(END_EVENT, END_CANCEL_EVENT, END_ERROR_EVENT, END_TERMINATE_EVENT));
    }

    @Override
    protected FlowElement convertInternal(BpmnModel bpmnModel, mxGraphModel graphModel, mxCell cell) {
        EndEvent endEvent = new EndEvent();
        parseEventDefinition(cell).ifPresent(endEvent::addEventDefinition);
        return endEvent;
    }

    private Optional<EventDefinition> parseEventDefinition(mxCell cell) {
        return MxCellUtils.parseShape(cell).map(shape -> {
            switch (shape) {
                case END_CANCEL_EVENT:
                    return new CancelEventDefinition();
                case END_ERROR_EVENT:
                    ErrorEventDefinition errorEvent = new ErrorEventDefinition();
                    errorEvent.setErrorCode(cell.getAttribute("errorCode"));
                    return errorEvent;
                case END_TERMINATE_EVENT:
                    TerminateEventDefinition terminateEvent = new TerminateEventDefinition();
                    return terminateEvent;
                default:
                    return null;
            }
        });
    }
}
