package eu.dnetlib;

import static org.junit.Assert.assertEquals;

import java.io.StringReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import org.junit.Test;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import eu.dnetlib.miscutils.functional.xml.ApplyXslt;

/**
 * Unit test for simple App.
 */
public class AppTest {

	@Test
	public void testXslt() {
		String res = new ApplyXslt(getXslt()).evaluate(getXml());
		System.out.println("******************");
		System.out.println(res);
		System.out.println("******************");
	}

	@Test
	public void testXpath() throws DocumentException {
		SAXReader reader = new SAXReader();
		Document doc = reader.read(new StringReader("<a><b>test</b></a>"));
		assertEquals("", doc.valueOf("//c"));
		assertEquals("test", doc.valueOf("//b"));
	}

	public static String javaMethod(final NodeList list) {
		System.out.println("******************");
		System.out.println("TYPE   : " + list.toString());
		System.out.println("LENGTH : " + list.getLength());
		for (int i = 0; i < list.getLength(); i++) {
			Node node = list.item(i);

			System.out.println("ELEM " + i + ": " + node.getLocalName());
		}

		System.out.println("******************");
		return "ACUS";
	}

	private String getXml() {
		final StringWriter sw = new StringWriter();
		sw.append("<?xml version='1.0' encoding='UTF-8'?>\n");
		sw.append("<record>\n");
		sw.append("<metadata>\n");
		sw.append("<a>A text value</a>\n");
		sw.append("<b attr='attribute value'/>\n");
		sw.append("</metadata>\n");
		sw.append("</record>\n");

		return sw.toString();
	}

	private String getXslt() {
		final StringWriter sw = new StringWriter();

		sw.append("<?xml version='1.0' encoding='UTF-8'?>\n");
		sw.append("<xsl:stylesheet version='1.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:dnet='eu.dnetlib.AppTest' exclude-result-prefixes='xsl dnet'>\n");
		sw.append("<xsl:output omit-xml-declaration='yes' indent='yes'/>\n");
		sw.append("<xsl:template match='/*'>\n");
		sw.append("<xsl:variable name='metadata' select=\"//*[local-name()='metadata']/*\" />\n");
		sw.append("<ROWS>\n");
		sw.append("<xsl:value-of select='dnet:javaMethod($metadata)'/>\n");
		sw.append("</ROWS>\n");
		sw.append("</xsl:template>\n");
		sw.append("</xsl:stylesheet>\n");
		return sw.toString();
	}

	@Test
	public void encodetest() throws UnsupportedEncodingException {
		String theUrl = "http://europepmc.org/GrantLookup/grants.php?&f%5B%5D=WT&range=all&format=xml&output=export";
		String encoded = URLEncoder.encode(theUrl, "UTF-8");
		System.out.println(encoded);
	}

}
