/*
 * FichasPrinter.java
 *
 * Created on 20 de Fevereiro de 2006, 0:43
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package siprp.impressaofichas;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;

import javax.xml.transform.TransformerFactory;

import siprp.printer.Printer;

import com.evolute.utils.Singleton;
import com.evolute.utils.date.DateUtils;
import com.evolute.utils.fop.FOPCreator;
import com.evolute.utils.fop.FOPPrinter;
import com.evolute.utils.fop.FOPPrinterConstants;
import com.evolute.utils.fop.PDFCreator;
import com.evolute.utils.strings.StringPlainer;
import com.evolute.utils.ui.DialogException;
import com.evolute.utils.xml.SimpleXMLElement;

/**
 *
 * @author Frederico
 */
public class FichasPrinter extends Thread
{
	protected static final DateFormat D_F = DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "pt", "PT" ) );
	protected static final DateFormat D_F_L = DateFormat.getDateInstance( DateFormat.LONG, new Locale( "pt", "PT" ) );
	
	private ImpressaoFichasDataProvider provider;
	
	protected Integer ids[];
	protected String printerName;
	protected String listPath;
	protected String nomeEmpresa;
	protected String nomeEstabelecimento;
	
	/** Creates a new instance of FichasPrinter */
	public FichasPrinter( Integer ids[], String printerName, String listPath,
							String nomeEmpresa, String nomeEstabelecimento )
	{
		this.ids = ids;
		this.printerName = printerName;
		this.listPath = listPath;
		this.nomeEmpresa = nomeEmpresa;
		this.nomeEstabelecimento = nomeEstabelecimento;
	}
	
	public void run()
	{
		try
		{
			SimpleXMLElement root = new SimpleXMLElement( "LISTA_FICHAS" );
			for( int n = 0; n < ids.length; n++ )
			{
				print( ids[ n ] );
				Object dados[] = provider.getDadosForExameID( ids[ n ] );
				SimpleXMLElement linha = new SimpleXMLElement( "FICHA" );
				linha.addElement( new SimpleXMLElement( "NOME", ( String ) dados[ 0 ] ) );
				linha.addElement( new SimpleXMLElement( "DATA_EXAME", D_F.format( ( Date ) dados[ 1 ] ) ) );
				linha.addElement( new SimpleXMLElement( "DATA_PROXIMO_EXAME", dados[ 2 ] != null ? D_F.format( ( Date ) dados[ 2 ] ) : "n/d" ) );
				root.addElement( linha );
				
				try
				{
					sleep( (n % 5 == 0 && n > 0) ? 3000 : 2000 );
				}
				catch( InterruptedException iex )
				{
				}
			}
			Date today = ( Date ) Singleton.getInstance( Singleton.TODAY );
			Calendar cal = Calendar.getInstance();
			cal.setTime( today );
			SimpleXMLElement data = new SimpleXMLElement( "DATA_EXTENSO", DateUtils.WEEKDAYS_FULL_PT[ cal.get( Calendar.DAY_OF_WEEK ) - Calendar.MONDAY ]
																			+ ", " + D_F_L.format( today ) );
			root.addElement( data );
			TransformerFactory tFactory = TransformerFactory.newInstance();
			String xml = root.toString();
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			FOPCreator creator = FOPCreator.getFOPCreator();
			InputStream xmlIn = new ByteArrayInputStream( xml.getBytes() );
			creator.createFOfromXML( xmlIn,
								FichasPrinter.class.getClassLoader().getResourceAsStream( 
									"siprp/impressaofichas/lista_fichas.xsl" ), 
									out );
			byte toPrint[] = out.toByteArray();
			ByteArrayInputStream in = new ByteArrayInputStream( toPrint );
			Hashtable printOptions = new Hashtable();
//System.out.println( "OUT: " + out.toString() );
//			printOptions.put( FOPPrinterConstants.FOP_MANDATORY_PRINTER_NAME, printerName );
			FOPPrinter.getFOPPrinter().printFO( in, false, true, printOptions );
			byte []pdfData = PDFCreator.getPDFCreator().createPdfFromFo( toPrint );
			File dir = new File( new File( listPath ), StringPlainer.convertString( nomeEmpresa ).replace( ' ', '_' ) );
			if( !dir.exists() )
			{
				dir.mkdir();
			}
			String fileName = StringPlainer.convertString( nomeEstabelecimento ).replace( ' ', '_' )
								+ "_" + DateUtils.plainFormatDate( today ) + ".pdf";
			FileOutputStream fos = new FileOutputStream( new File( dir, fileName ) );
			fos.write( pdfData );
			fos.close();
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a imprimir", true );
		}
		ids = null;
	}
	
	private void print( Integer exameID )
		throws Exception
	{
		if( provider == null )
		{
			provider = ( ImpressaoFichasDataProvider ) ImpressaoFichasDataProvider.getProvider();
		}
//		MetaObject exame = fdpProvider.load( fdpProvider.EXAMES, new DBKey( exameID ) );		
//		ExameData exame = (ExameData) JDO.load( ExameData.class, exameID );
//		byte pdf[] = (byte []) exame.get( ExameData.PDF );
		
		if( /* !printFO( exameID ) && */!printPDF( exameID ) )
		{
			throw new Exception( "N\u00e3o existe exame" );
		}
	}
	
	private boolean printFO(int exameID) throws Exception
	{
		boolean result = false;
		byte[] fo = provider.getFO( exameID );
		if(fo != null)
		{
			Printer.printFO( fo );
			result = true;
		}
		return result;
	}
	
	private boolean printPDF(int exameID) throws Exception
	{
		boolean result = false;
		byte pdf[] = provider.getPDF( exameID );
		if( pdf != null )
		{
			String nomeFicheiro = StringPlainer.convertString( provider.getNomeTrabalhadorForExameID( exameID ) );
			String split[] = nomeFicheiro.split( " " );
			nomeFicheiro = "";
			for( int n = 0; n < split.length; n++ )
			{
				nomeFicheiro += split[n] + "_";
			}
			Printer.printPDF( pdf, nomeFicheiro, printerName );
			result = true;
		}
		return result;
	}
}
