package eu.dnetlib.miscutils.functional.xml;

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

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

import org.springframework.core.io.Resource;
import org.w3c.dom.Node;

/**
 * Applies a stylesheet to a XML DOM and returns an XML string.
 * 
 * @author marko
 * 
 */
public class ApplyXsltDom extends AbstractApplyXslt<Node> {

	public ApplyXsltDom(Resource xslt) {
		super(xslt);
	}

	public ApplyXsltDom(Source xslt, String name) {
		super(xslt, name);
	}

	public ApplyXsltDom(Source xslt) {
		super(xslt);
	}

	public ApplyXsltDom(String xslt, String name) {
		super(xslt, name);
	}

	public ApplyXsltDom(String xslt) {
		super(xslt);
	}

	public ApplyXsltDom(Resource xslt, Map<String, String> parameters) {
		super(xslt, parameters);
	}

	public ApplyXsltDom(Source xslt, String name, Map<String, String> parameters) {
		super(xslt, name, parameters);
	}

	public ApplyXsltDom(String xslt, String name, Map<String, String> parameters) {
		super(xslt, name, parameters);
	}

	@Override
	public Source toStream(Node input) {
		return new DOMSource(input);
	}
	
	@Override
	public String toString(Node input) {
		return nodeToString(input);
	}

	private String nodeToString(Node node) {
		StringWriter sw = new StringWriter();
		try {
			Transformer t = TransformerFactory.newInstance().newTransformer();
			t.setOutputProperty(OutputKeys.INDENT, "yes");
			t.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
			t.transform(new DOMSource(node), new StreamResult(sw));
		} catch (TransformerException te) {
			System.out.println("nodeToString Transformer Exception");
		}
		return sw.toString();
	}

}
