package eu.dnetlib.functionality.modular.ui.workflows.util.functions;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.dom4j.Node;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;

import eu.dnetlib.msro.workflows.util.WorkflowParam;
import eu.dnetlib.msro.workflows.util.WorkflowParamUI;

public class NodeToWorkflowParam implements Function<Node, WorkflowParam> {
	
	private Map<String, List<WorkflowParamUI>> mapUis = Maps.newHashMap();
		
	public NodeToWorkflowParam(final Map<String, List<WorkflowParamUI>> mapUis) {
		this.mapUis = mapUis;
	}

	@Override
	public WorkflowParam apply(final Node n) {
		final String key = n.valueOf("@name");
		final boolean required = "true".equalsIgnoreCase(n.valueOf("@required"));
		final String type = n.valueOf("@type");
		final String function = n.valueOf("@function");
		final String value = n.getText();
		final boolean userParam = "user".equals(n.valueOf("@managedBy"));
		final String category = n.valueOf("@category");
		final List<WorkflowParamUI> uis = calculateUis(category);
		
		return new WorkflowParam(key, value, required, userParam, type, function, uis);
	}

	private List<WorkflowParamUI> calculateUis(final String category) {
		if (!StringUtils.isEmpty(category) && mapUis.containsKey(category)) {
			return mapUis.get(category);
		} else {
			return Lists.newArrayList();
		}
	}

}
