package com.huigou.explorer.converters.bpmn;

import com.alibaba.fastjson.JSONArray;
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.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.apache.commons.lang3.StringUtils;

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

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

    public UserTaskConverter() {
        super(Collections.singletonList(Shape.USER_TASK));
    }

    @Override
    protected FlowElement convertInternal(BpmnModel bpmnModel, mxGraphModel graphModel, mxCell cell) {
        UserTask userTask = new UserTask();
        userTask.setFormKey(cell.getAttribute("formKey"));
        userTask.setAssignee(cell.getAttribute("assignee"));
        userTask.setSkipExpression(cell.getAttribute("skipExpression"));
        userTask.setDueDate(cell.getAttribute("dueDate"));
        userTask.setCategory(cell.getAttribute("category"));
        Optional.ofNullable(cell.getAttribute("candidateUsers"))
                .filter(StringUtils::isNotBlank)
                .map(candidateUsers -> candidateUsers.split(","))
                .map(Arrays::asList)
                .ifPresent(userTask::setCandidateUsers);
        Optional.ofNullable(cell.getAttribute("candidateGroups"))
                .filter(StringUtils::isNotBlank)
                .map(candidateGroups -> candidateGroups.split(","))
                .map(Arrays::asList)
                .ifPresent(userTask::setCandidateGroups);
        Optional.ofNullable(cell.getAttribute("taskListeners"))
                .filter(StringUtils::isNotBlank)
                .map(JSONArray::parseArray)
                .map(getActivitiListenerParser()::parse)
                .ifPresent(userTask::setTaskListeners);
        return userTask;
    }
}
