package eu.dnetlib.msro.workflows.metawf;

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

import javax.annotation.Resource;

import org.apache.commons.lang.StringEscapeUtils;
import org.springframework.beans.factory.annotation.Required;

import eu.dnetlib.enabling.is.registry.rmi.ISRegistryException;
import eu.dnetlib.enabling.is.registry.rmi.ISRegistryService;
import eu.dnetlib.enabling.locators.UniqueServiceLocator;

public class WorkflowTree {

	private String id;

	private String name;

	private WorkflowStartModeEnum start = WorkflowStartModeEnum.auto;

	private List<WorkflowTree> children;

	private org.springframework.core.io.Resource template;

	@Resource
	private UniqueServiceLocator serviceLocator;

	public void populateMetaWfXml(final StringWriter sw) {
		sw.append("<WORKFLOW id='" + StringEscapeUtils.escapeXml(id) + "' name='" + StringEscapeUtils.escapeXml(name) + "'");

		if (children == null || children.isEmpty()) {
			sw.append(" />");
		} else {
			sw.append(">");
			for (WorkflowTree child : children) {
				child.populateMetaWfXml(sw);
			}
			sw.append("</WORKFLOW>");
		}
	}

	public int registerAllWorkflows(final Map<String, String> params) throws ISRegistryException, IOException {
		int count = 0;

		if (this.id == null || this.id.isEmpty()) {
			final String profile = WorkflowProfileCreator.generateProfile(name, "aggregator", start, params, template);
			this.id = serviceLocator.getService(ISRegistryService.class).registerProfile(profile);
			count++;
		}

		if (children != null) {
			for (WorkflowTree child : children) {
				count += child.registerAllWorkflows(params);
			}
		}
		return count;
	}

	public String getId() {
		return id;
	}

	public List<WorkflowTree> getChildren() {
		return children;
	}

	public void setChildren(final List<WorkflowTree> children) {
		this.children = children;
	}

	public String getName() {
		return name;
	}

	@Required
	public void setName(final String name) {
		this.name = name;
	}

	public org.springframework.core.io.Resource getTemplate() {
		return template;
	}

	@Required
	public void setTemplate(final org.springframework.core.io.Resource template) {
		this.template = template;
	}

	public WorkflowStartModeEnum getStart() {
		return start;
	}

	public void setStart(final WorkflowStartModeEnum start) {
		this.start = start;
	}

}
