package siprp.planoactuacao.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 PlanoActuacaoPDFCreator
{
	
	public byte[] createPDF( Integer planoId, boolean web ) throws Exception
	{
		PlanoActuacaoToPrint plano = PlanoActuacaoPrintDataProvider.getProvider( web ).getPlanoToPrint( planoId );
		Document foDoc = new Document( plano.toJdomElement() );
		XMLOutputter outputter = new XMLOutputter(Format.getPrettyFormat());
		ByteArrayOutputStream foBaos = new ByteArrayOutputStream();
		outputter.output( foDoc, foBaos );

			
		byte fo[] = 
			applyTemplate(
				getClass().getClassLoader().getResourceAsStream( 
						PlanoActuacaoPrintDataProvider.getProvider( web ).empresaUsaPlanoAlargadoPorPlanoId( planoId ) ? 
								"siprp/planoactuacao/print/plano_actuacao_alargado.xsl"
								: "siprp/planoactuacao/print/plano_actuacao.xsl" ),
				new ByteArrayInputStream( foBaos.toByteArray() ) );
		

//		FileOutputStream fos = new FileOutputStream("/home/jneto/Desktop/a.fo");
//		fos.write(fo);
		

		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();
	}
	
}
