package eu.dnetlib.miscutils.functional.xml;

import static org.junit.Assert.assertEquals;

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

import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import org.dom4j.Document;
import org.dom4j.io.SAXReader;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.junit.MockitoJUnitRunner;

@RunWith(MockitoJUnitRunner.class)
public class DnetFunctionsTest {
	
	private static final String XSLT = 
		"<?xml version='1.0' encoding='UTF-8'?>" + 
		"<xsl:stylesheet version='2.0' xmlns:xsl='http://www.w3.org/1999/XSL/Transform' xmlns:dnet='eu.dnetlib.miscutils.functional.xml.DnetXsltFunctions'>" +
        "<xsl:template match='/'>" +
		"   <OUTS>" +
        "      <OUTPUT decade='{dnet:decade(//INPUT/DATE)}' />" +
        "      <OUTPUT year='{dnet:extractYear(//INPUT/DATE)}' />" +
        "   </OUTS>" +
        "</xsl:template>" +
        "</xsl:stylesheet>";
	 
	private Transformer transformer;
	
	@Before
	public void setUp() {
		try {
			transformer = TransformerFactory.newInstance().newTransformer(new StreamSource(new StringReader(XSLT)));
		} catch (Exception e) {
			System.out.println("**** INITIALIZATION FAILED ****");
		}
	}
	
	@Test
	public void testDecade_1() throws Exception {
		assertEquals("1980-1989", process("primi anni 80", "decade"));
	}
	
	@Test
	public void testDecade_2() throws Exception {
		assertEquals("2000-2009", process("04-05-2007", "decade"));
	}

	@Test
	public void testDecade_3() throws Exception {
		assertEquals("1960-1969", process("1964", "decade"));
	}
		
	@Test
	public void testDecade_4() throws Exception {
		assertEquals("n/a", process("XXXXXXXXXXXX", "decade"));
	}

	@Test
	public void testDecade_5() throws Exception {
		assertEquals("1880-1889", process("    1887-01-01    ", "decade"));
	}
	
	@Test
	public void testDecade_6() throws Exception {
		assertEquals("1880-1889", process("\n\n    1887-01-01    \n\n", "decade"));
	}
	
	@Test
	public void testDecade_7() throws Exception {
		assertEquals("1840-1849", process("   1840-03-05   ", "decade"));
	}
	
	@Test
	public void testYear_1() throws Exception {
		assertEquals("1840", process("1840-03-05", "year"));
	}
	
	@Test
	public void testYear_2() throws Exception {
		assertEquals("1840", process("1840/03/05", "year"));
	}
	
	private String process(String s, String attr) throws Exception {
		String xml = "<INPUT><DATE>" + s + "</DATE></INPUT>";
		
		StringWriter strw = new StringWriter();
		transformer.transform(new StreamSource(new StringReader(xml)), new StreamResult(strw));
	
		Document document = (new SAXReader()).read(new StringReader((strw.toString())));
		
		System.out.println(document.asXML());
		
		String res = document.valueOf("/OUTS/OUTPUT/@" + attr);
	
		System.out.println(s + " --> " + res);
		
		return res;
	}

}
