package eu.dnetlib.miscutils.functional.xml;

import java.io.StringWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerFactoryConfigurationError;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Node;

import eu.dnetlib.miscutils.functional.UnaryFunction;

public class SerializeXml implements UnaryFunction<String, Node> {

	Transformer transformer;

	public SerializeXml() {
		try {
			this.transformer = TransformerFactory.newInstance().newTransformer();
			transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		} catch (TransformerConfigurationException e) {
			throw new IllegalStateException(e);
		} catch (TransformerFactoryConfigurationError e) {
			throw new IllegalStateException(e);
		}
	}

	@Override
	public String evaluate(Node arg) {
		StreamResult result = new StreamResult(new StringWriter());
		DOMSource source = new DOMSource(arg);
		try {
			transformer.transform(source, result);
			return result.getWriter().toString();
		} catch (TransformerException e) {
			throw new IllegalStateException(e);
		}
	}

}
