package eu.dnetlib.msro.workflows.xslt;

import java.io.IOException;
import java.io.InputStream;
import java.io.StringReader;
import java.io.StringWriter;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;

import eu.dnetlib.enabling.is.lookup.rmi.ISLookUpException;
import eu.dnetlib.miscutils.functional.xml.ApplyXslt;
import eu.dnetlib.miscutils.functional.xml.IndentXmlString;
import org.apache.commons.io.IOUtils;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;

public class LayoutToRecordStylesheetTest {

	private static final String LAYOUT_TO_RECORD_STYLESHEET_XSL = "/eu/dnetlib/msro/workflows/xslt/layoutToRecordStylesheet.xsl";

	private static final String MDFORMAT_FIELDS = "/eu/dnetlib/msro/workflows/xslt/fields.xml";

	private static final String OAF_RECORD = "/eu/dnetlib/msro/workflows/xslt/exampleRecord.xml";

	@Test
	public void test1() throws ISLookUpException, IOException, TransformerException {
		String xsl = prepareXslt("DMF");
		assertNotNull(xsl);
		assertFalse(xsl.isEmpty());

		System.out.println(xsl);

		ApplyXslt xslt = new ApplyXslt(xsl);

		String indexRecord = xslt.evaluate(readFromClasspath(OAF_RECORD));

		assertNotNull(indexRecord);
		assertFalse(indexRecord.isEmpty());

		System.out.println(IndentXmlString.apply(indexRecord));

		// StreamingInputDocumentFactory factory = new StreamingInputDocumentFactory();
		//
		// SolrInputDocument doc = factory.parseDocument(DateUtils.now_ISO8601(), indexRecord, "dsId", "dnetResult");
		// assertNotNull(doc);
		// assertFalse(doc.isEmpty());

		// System.out.println(doc);

	}

	protected String prepareXslt(final String format) throws ISLookUpException, IOException, TransformerException {

		final TransformerFactory factory = TransformerFactory.newInstance();

		final Transformer layoutTransformer = factory.newTransformer(streamSource(LAYOUT_TO_RECORD_STYLESHEET_XSL));

		final StreamResult layoutToXsltXslt = new StreamResult(new StringWriter());

		layoutTransformer.setParameter("format", format);
		layoutTransformer.transform(streamSource(MDFORMAT_FIELDS), layoutToXsltXslt);

		String layoutToXsltXsltString = layoutToXsltXslt.getWriter().toString();
		System.out.println(IndentXmlString.apply(layoutToXsltXsltString) + "\n\n\n");

		return layoutToXsltXsltString;
	}

	private StreamSource streamSource(final String s) throws IOException {
		return new StreamSource(new StringReader(readFromClasspath(s)));
	}

	private String readFromClasspath(final String s) throws IOException {
		ClassPathResource resource = new ClassPathResource(s);
		InputStream inputStream = resource.getInputStream();
		return IOUtils.toString(inputStream);
	}

}
