package eu.dnetlib.msro.workflows.metawf;

import java.io.IOException;
import java.util.Map;

import org.antlr.stringtemplate.StringTemplate;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;

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

import eu.dnetlib.msro.workflows.util.WorkflowsConstants;

public class WorkflowProfileCreator {

	private static final Resource wfTemplate = new ClassPathResource("/eu/dnetlib/msro/workflows/templates/workflow.xml.st");

	public static String generateProfile(final String name,
			final String type,
			final WorkflowStartModeEnum startMode,
			final Map<String, String> params,
			final Resource confTemplate)
			throws IOException {

		final StringTemplate conf = new StringTemplate(IOUtils.toString(confTemplate.getInputStream()));
		conf.setAttribute("params", Maps.transformValues(params, new Function<String, String>() {

			@Override
			public String apply(final String s) {
				return StringEscapeUtils.escapeXml(s);
			}
		}));

		final StringTemplate profile = new StringTemplate(IOUtils.toString(wfTemplate.getInputStream()));
		profile.setAttribute("name", name);
		profile.setAttribute("type", type);
		profile.setAttribute("priority", WorkflowsConstants.DEFAULT_WF_PRIORITY);
		profile.setAttribute("conf", conf.toString());
		profile.setAttribute("startMode", startMode);

		return profile.toString();
	}
}
