package com.huigou.explorer.converters.mxgraph;

import com.alibaba.fastjson.JSON;
import com.mxgraph.model.mxCell;
import org.activiti.bpmn.model.BaseElement;
import org.activiti.bpmn.model.ExtensionAttribute;
import org.activiti.bpmn.model.HasExecutionListeners;
import org.apache.commons.lang3.StringUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author yonghuan
 */
public abstract class AbstractMxElementConverter implements MxElementConverter {

    /**
     * 解析流程事件监听器。
     */
    protected final void parseExecutionListeners(HasExecutionListeners hasExecutionListeners, mxCell cell) {
        List<Map<String, Object>> listeners = hasExecutionListeners.getExecutionListeners().stream().map(activitiListener -> {
            Map<String, Object> listener = new HashMap<>(3);
            listener.put("event", activitiListener.getEvent());
            listener.put("implementationType", activitiListener.getImplementationType());
            listener.put("implementation", activitiListener.getImplementation());
            listener.put("fieldExtensions", activitiListener.getFieldExtensions());
            return listener;
        }).collect(Collectors.toList());
        if (listeners.size() > 0) {
            cell.setAttribute("executionListeners", JSON.toJSONString(listeners));
        }
    }

    /**
     * 从activiti模型元素中获取field扩展元素的值。
     *
     * @param be        activiti模型元素
     * @param fieldName 字段名称
     * @return 字段值
     */
    protected final Optional<ExtensionAttribute> getFieldExtensionElement(BaseElement be, String fieldName) {
        return be.getExtensionElements().getOrDefault("field", Collections.emptyList())
                .stream()
                .flatMap(field -> field.getAttributes().get(fieldName).stream())
                .findAny()
                .filter(attr -> StringUtils.isNotBlank(attr.getValue()));
    }

}
