package eu.dnetlib.common.utils;

import java.io.StringReader;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Node;
import org.dom4j.XPath;
import org.dom4j.io.SAXReader;

public class XMLUtils {

	private static final SAXReader reader = new SAXReader();
	private static Map<String, String> nsMap = new HashMap<String, String>();

	public static Document getDocument(String document)throws XMLException{
		try{
			return reader.read(new StringReader(document));
		}catch(DocumentException e){
			throw new XMLException(e);
		}		
	}
	
	public static void setNamespaces(Map<String, String> nsMap){
		XMLUtils.nsMap = nsMap;
	}
	
	public static String evaluate(String document, String expression)throws XMLException{
		XPath xpath =  DocumentHelper.createXPath(expression);
		xpath.setNamespaceURIs(XMLUtils.nsMap);
		return xpath.valueOf(getDocument(document));
	}
	
	public static String evaluate(Node document, String expression)throws XMLException{
		XPath xpath =  DocumentHelper.createXPath(expression);
		xpath.setNamespaceURIs(XMLUtils.nsMap);
		return xpath.valueOf(document);		
	}
	
	@SuppressWarnings("unchecked")
	public static List<Node> getNodes(Document document, String expression)throws XMLException{
		XPath xpath =  DocumentHelper.createXPath(expression);
		xpath.setNamespaceURIs(XMLUtils.nsMap);
		return xpath.selectNodes(document, xpath);
	}
}
