package siprp.higiene.relatorio.print;

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

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

import siprp.Main;
import siprp.util.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(Format.getPrettyFormat());
		ByteArrayOutputStream foBaos = new ByteArrayOutputStream();
//		FileOutputStream fos = new FileOutputStream("/home/jneto/a.xml");
		outputter.output( foDoc, foBaos );
//		outputter.output( foDoc, fos );
		
//		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 ) );

		
		//FIXME: FOP COPIADO
		PDFCreator.setUserConfig(Main.fopConfigFile);
		PDFCreator pdfCreator = PDFCreator.getPDFCreator();
		
		
		byte pdf[] = pdfCreator.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();
	}
	
}
