package siprp.higiene.relatorio.print;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;

import org.jdom.Document;
import org.jdom.output.XMLOutputter;

import com.evolute.utils.fop.PDFCreator;
import com.evolute.utils.xml.XSLTransformer;

public class RelatorioPDFCreator
{
	
	public byte[] createPDF( Integer relatorioId ) throws Exception
	{
		RelatorioToPrint relatorio = RelatorioPrintDataProvider.getProvider().getRelatorioToPrint( relatorioId );
		Document foDoc = new Document( relatorio.toJdomElement() );
		XMLOutputter outputter = new XMLOutputter();
		ByteArrayOutputStream foBaos = new ByteArrayOutputStream();
		outputter.output( foDoc, foBaos );
//		System.out.println( new String( foBaos.toByteArray() ) );
		byte fo[] = 
			applyTemplate(
				getClass().getClassLoader().getResourceAsStream( 
						"siprp/higiene/relatorio/print/relatorio.xsl" ),
						new ByteArrayInputStream( foBaos.toByteArray() ) );
//		System.out.println( new String( fo ) );
		byte pdf[] = PDFCreator.getPDFCreator().createPdfFromFo( fo );
		return pdf;
	}
	
	public byte[] applyTemplate( InputStream xsl, InputStream dataStream ) throws Exception
	{
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		XSLTransformer.getXSLTransformer().transform( dataStream, xsl, baos );
		return baos.toByteArray();
	}
	
}
