package eu.dnetlib.xml.database.exist;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

/**
 * Exist has an internal DOM implementation.
 *
 * @author marko
 *
 */
@SuppressWarnings("deprecation")
public class ExistDOMConverter {

	/**
	 * convert a DOM document to InputSource on which you can run an XPath.
	 *
	 * The internal eXist DOM implementation has some problems.
	 *
	 * @param input
	 *            DOM document
	 * @return sax input source
	 * @throws IOException
	 *             happens ?
	 */
	public InputSource asInputSource(final Document input) throws IOException {
		return new InputSource(new StringReader(asString(input)));
	}

	/**
	 * serialize a dom document to a string.
	 *
	 * TODO: avoid using deprecated XMLSerializer
	 *
	 * cannot use Transformer because eXist DOM impl is incomplete.
	 *
	 * @param input
	 *            DOM document
	 * @return sax input source
	 * @throws IOException
	 *             happens ?
	 */

	public String asString(final Document input) throws IOException {
		final StringWriter writer = new StringWriter();

		new XMLSerializer(writer, new OutputFormat()).serialize(input.getDocumentElement());

		return writer.toString();
	}

	/**
	 * convert a DOM document to a w3c DOM Document on which you can run an XPath.
	 *
	 * The internal eXist DOM implementation has some problems.
	 *
	 * @param input
	 *            input eXist DOM document
	 * @return good DOM document
	 * @throws IOException
	 *             happens
	 * @throws ParserConfigurationException
	 *             happens
	 * @throws SAXException
	 *             happens
	 */
	public Document asDocument(final Document input) throws IOException, ParserConfigurationException, SAXException {
		final DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
		return builder.parse(asInputSource(input));
	}
}
