package eu.dnetlib.msro.workflows.sarasvati.loader;

import java.io.File;
import java.io.FileOutputStream;
import java.io.StringReader;

import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.springframework.beans.factory.annotation.Required;

import com.googlecode.sarasvati.Graph;
import com.googlecode.sarasvati.mem.MemEngine;

public class GraphLoader {
	private MemEngine engine;
	
	private static final Log log = LogFactory.getLog(GraphLoader.class);
	
	public Graph loadGraph(String xml) throws Exception {
		final File tmpFile = File.createTempFile("wftfs", null);
		try {
			IOUtils.copy(new StringReader(xml), new FileOutputStream(tmpFile));
			
			SAXReader reader = new SAXReader();
			Document doc = reader.read(tmpFile);
			String graphName = doc.valueOf("/process-definition/@name");
			
			getEngine().getLoader().load(tmpFile);

			final Graph graph = getEngine().getRepository().getLatestGraph(graphName);
			if (graph == null) {
				throw new IllegalArgumentException("graph called " + graphName + " doesn't exist");
			}
			return graph;
		} catch (DocumentException e) {
			log.error("Error parsing xml: " + xml, e);
			throw e;
		} finally {
			tmpFile.delete();
		}
	}
	

	public MemEngine getEngine() {
		return engine;
	}

	@Required
	public void setEngine(MemEngine engine) {
		this.engine = engine;
	}
	
}
