package nl.idgis.portal.harvester.util;

import java.util.ArrayList;
import java.util.List;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.Document;
import org.w3c.dom.NodeList;

public class MetadataDocument {
	private final Document d;
	private final XPath xp;
	
	public MetadataDocument(Document d, XPath xp) {
		this.d = d;
		this.xp = xp;
	}
	
	public String getString(String path) throws XPathExpressionException {
		if(!path.endsWith("text()") && !path.endsWith("@uuidref") && !path.endsWith("codeListValue")) {
			throw new RuntimeException("path should end with text() or @uuidref");
		}
		
		NodeList nl = (NodeList) xp.evaluate(path, d, XPathConstants.NODESET);
		
		if(nl.item(0) != null) {
			return nl.item(0).getNodeValue().trim();
		}
		
		return null;
	}
	
	public List<String> getStrings(String path) throws Exception {
		if(!path.endsWith("text()") && !path.endsWith("@uuidref") && !path.endsWith("codeListValue")) {
			throw new RuntimeException("path should end with text() or @uuidref");
		}
		
		List<String> values = new ArrayList<>();
		
		NodeList nl = (NodeList) xp.evaluate(path, d, XPathConstants.NODESET);
		
		for(int i = 0; i < nl.getLength(); i++) {
			values.add(nl.item(i).getNodeValue());
		}
		
		return values;
	}
}

@@ -82,20 +82,83 @@
 va.util.
-List
+Arrays;%0D%0Aimport java.util.List;%0D%0Aimport java.util.stream.Collectors
 ;%0D%0A%0D%0Aimp
@@ -890,16 +890,34 @@
 %09return 
+handleLineEndings(
 nl.item(
@@ -940,16 +940,17 @@
 ).trim()
+)
 ;%0D%0A%09%09%7D%0D%0A
@@ -1112,32 +1112,33 @@
 !path.endsWith(%22
+@
 codeListValue%22))
@@ -1191,35 +1191,33 @@
  end with text()
- or
+,
  @uuidref%22);%0D%0A%09%09
@@ -1201,32 +1201,50 @@
 text(), @uuidref
+ or @codeListValue
 %22);%0D%0A%09%09%7D%0D%0A%09%09%0D%0A%09%09
@@ -1426,16 +1426,34 @@
 ues.add(
+handleLineEndings(
 nl.item(
@@ -1470,16 +1470,17 @@
 Value())
+)
 ;%0D%0A%09%09%7D%0D%0A
@@ -1505,11 +1505,197 @@
 s;%0D%0A%09%7D%0D%0A
+%09%0D%0A%09private String handleLineEndings(String value) %7B%0D%0A%09%09return %0D%0A%09%09%09Arrays.asList(value.split(%22%5Cn%22))%0D%0A%09%09%09%09.stream()%0D%0A%09%09%09%09.map(s -%3E s.trim())%0D%0A%09%09%09%09.collect(Collectors.joining(%22 %22));%0D%0A%09%7D%0D%0A
 %7D%0D%0A

Handle line endings for xml elements