package com.delcyon.core.tags;

import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Set;
import java.util.Map.Entry;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;
import org.jdom.transform.JDOMResult;
import org.jdom.transform.JDOMSource;

public class XBLIncludeTag extends SimpleTagSupport
{

	private String name;
	// load the transformation factory
	TransformerFactory factory = TransformerFactory.newInstance();
	XMLOutputter outputter = new XMLOutputter(Format.getCompactFormat());
	Hashtable<String, String> parameterHashtable = new Hashtable<String, String>();

	/** transfors a JDOM in another JDOM **/
	public Document transform(Document xml_doc, Document xsl_doc)
	{
		try
		{
			// make a space for the result
			JDOMResult result = new JDOMResult();
			// wrap up the xml
			JDOMSource xml_source = new JDOMSource(xml_doc);
			// wrap up the xsl
			JDOMSource xsl_source = new JDOMSource(xsl_doc);
			// run the transformation
			Transformer transformer = factory.newTransformer(xsl_source);
			Set<Entry<String, String>> set = parameterHashtable.entrySet();
			for (Entry<String, String> entry : set)
			{
				transformer.setParameter(entry.getKey(), entry.getValue());
			}
			transformer.transform(xml_source, result);
			// return the resulting document
			return result.getDocument();
		} catch (Exception e)
		{
			e.printStackTrace();
		}
		// return null on error
		return null;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	@Override
	public void doTag() throws JspException, IOException
	{

		FileInputStream fileInputStream = new FileInputStream("./webapp/WEB-INF/resources/xbl/" + name + ".xbl");
		SAXBuilder saxBuilder = new SAXBuilder(false);

		try
		{
			Document xsldocument = saxBuilder.build("./webapp/WEB-INF/resources/xsl/search.xsl");
			Document xmldocument = saxBuilder.build("./webapp/WEB-INF/resources/xml-templates/" + name + ".xml");
			System.out.println("STARTING "+name+" TRANSFORM");
			Document resultDocument = transform(xmldocument, xsldocument);
			XMLOutputter xmlOutputter = new XMLOutputter(Format.getPrettyFormat());
			xmlOutputter.output(resultDocument, System.out);

		} catch (JDOMException e)
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		while (true)
		{
			byte[] buffer = new byte[4096];
			int bytesRead = fileInputStream.read(buffer);
			if (bytesRead < 0)
			{
				break;
			}
			getJspContext().getOut().print(new String(buffer).trim());
		}

	}
}