/*
 * RegistarPresencasWindow.java
 *
 * Created on January 31, 2007, 3:09 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package siprp.medicina.presencas;

import com.evolute.utils.data.IDObject;
import com.evolute.utils.data.MappableObject;
import com.evolute.utils.fop.FOPCreator;
import com.evolute.utils.fop.FOPPrinter;
import com.evolute.utils.tracker.TrackableWindow;
import com.evolute.utils.ui.DialogException;
import com.evolute.utils.ui.calendar.JCalendarPanel;
import com.evolute.utils.ui.panel.multipleactionlist.MultipleActionListPanel;
import java.awt.BorderLayout;
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Vector;
import javax.swing.*;
import org.jdom.*;
import org.jdom.output.*;
import siprp.clientes.ClientesDataProvider;
import siprp.medicina.MedicinaDataProvider;
import siprp.medicina.prestadores.PrestadoresDataProvider;

/**
 *
 * @author fpalma
 */
public class RegistarPresencasWindow extends JFrame
		implements ActionListener, TrackableWindow
{
	protected static final String PRINT_TEMPLATE = "/siprp/medicina/presencas/auxiliares.xsl";
	protected static final DateFormat D_F = DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "pt", "PT" ) );
	
	protected static final Integer PRESTADOR_ID_SIPRP = new Integer( -1 );
	protected static final Integer PRESTADOR_ID_TODOS = new Integer( -2 );
	
	protected static final IDObject PRESTADOR_SIPRP = new MappableObject( PRESTADOR_ID_SIPRP, "SIPRP" );
	protected static final IDObject PRESTADOR_TODOS = new MappableObject( PRESTADOR_ID_TODOS, "Todos" );
	
	protected JCalendarPanel dataPanel;
	protected JButton carregarButton;
	protected JComboBox prestadoresCombo;
	protected JButton recarregarPrestadoresButton;
	protected JButton imprimirAuxiliaresButton;
	protected JScrollPane listECDsScroll;
	protected JScrollPane listConsultasScroll;
	protected MultipleActionListPanel listECDsPanel;
	protected MultipleActionListPanel listConsultasPanel;
	
	protected MedicinaDataProvider provider;
	protected PrestadoresDataProvider prestadoresProvider;
	
	protected Presenca ECDS[];

	/** Creates a new instance of RegistarPresencasWindow */
	public RegistarPresencasWindow()
		throws Exception
	{
		provider = ( MedicinaDataProvider ) MedicinaDataProvider.getProvider();
		prestadoresProvider = PrestadoresDataProvider.getProvider();
		setupComponents();
		
	}
	
	private void setupComponents()
	{
		setTitle( "Presen\u00e7as" );
		setSize( 1000, 700 );
		JLabel dataLabel = new JLabel( "Data" );
		dataPanel = new JCalendarPanel( this );
		carregarButton = new JButton( "Carregar" );
		carregarButton.addActionListener( this );
		JLabel prestadoresLabel = new JLabel( "Prestador" );
		prestadoresCombo = new JComboBox ();
		recarregarPrestadoresButton = new JButton( "Recarregar Prestadores" );
		recarregarPrestadoresButton.addActionListener( this );
		imprimirAuxiliaresButton = new JButton( "Imprimir" );
		imprimirAuxiliaresButton.addActionListener( this );
		
		PresencasActionFactory realizouFactory = new PresencasActionFactory( PresencasActionFactory.REALIZOU );
		PresencasActionFactory realizouParcialmenteFactory = new PresencasActionFactory( PresencasActionFactory.REALIZOU_PARCIALMENTE );
		PresencasActionFactory trabalhadorDesmarcouFactory = new PresencasActionFactory( PresencasActionFactory.TRABALHADOR_DESMARCOU );
		PresencasActionFactory shstDesmarcouFactory = new PresencasActionFactory( PresencasActionFactory.SHST_DESMARCOU );
		PresencasActionFactory faltouFactory = new PresencasActionFactory( PresencasActionFactory.FALTOU );
		
		getContentPane().setLayout( new BorderLayout( 5, 5 ) );
		JPanel upperPanel = new JPanel();
		getContentPane().add( upperPanel, BorderLayout.NORTH );
		JTabbedPane tabbedPane = new JTabbedPane();
		getContentPane().add( tabbedPane, BorderLayout.CENTER );
		
		listECDsPanel = 
				new MultipleActionListPanel( 
					new PresencasActionFactory[]{ /*shstDesmarcouFactory, faltouFactory*/ },
					new PresencasActionFactory[]{ realizouFactory, realizouParcialmenteFactory,
													trabalhadorDesmarcouFactory, shstDesmarcouFactory, 
													faltouFactory } );
		listECDsScroll = new JScrollPane( listECDsPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
										JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		
		listConsultasPanel = 
				new MultipleActionListPanel( 
					new PresencasActionFactory[]{ /*shstDesmarcouFactory, faltouFactory*/ },
					new PresencasActionFactory[]{ realizouFactory, trabalhadorDesmarcouFactory, 
													shstDesmarcouFactory, faltouFactory } );
		listConsultasScroll = new JScrollPane( listConsultasPanel, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
										JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		
		tabbedPane.add( "ECDs", listECDsScroll );
		tabbedPane.add( "Consultas", listConsultasScroll );
		
		upperPanel.setLayout( new FlowLayout( FlowLayout.CENTER ) );
		upperPanel.add( dataLabel );
		upperPanel.add( dataPanel );
		upperPanel.add( carregarButton );
		upperPanel.add( prestadoresLabel );
		upperPanel.add( prestadoresCombo );
		upperPanel.add( recarregarPrestadoresButton );
		upperPanel.add( imprimirAuxiliaresButton );
		
		setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
		addWindowListener( new WindowAdapter(){
			public void windowClosing( WindowEvent e )
			{
				close();
			}
			
			public void windowOpened( WindowEvent e )
			{
//				setExtendedState( getExtendedState() | MAXIMIZED_BOTH );
			}
			
		} );
		dataPanel.setDate( new Date() );
		recarregarPrestadores();
		carregar();
	}

	public void actionPerformed( ActionEvent e )
	{
		Object source = e.getSource();
		if( source.equals( carregarButton ) )
		{
			carregar();
		}
		else if( source.equals( recarregarPrestadoresButton ) )
		{
			recarregarPrestadores();
		}
		else if( source.equals( imprimirAuxiliaresButton ) )
		{
			imprimirAuxiliares();
		}
	}

	public void refresh()
	{
	}

	public void open()
	{
		setVisible( true );
	}
	
	public void close()
	{
		SwingUtilities.invokeLater( new Runnable() {
			public void run()
			{
				setVisible( false );
				dispose();
			}
		} );
	}

	public boolean closeIfPossible()
	{
		close();
		return true;
	}
	
	protected void carregar()
	{
		ECDS = null;
		IDObject prestador = ( IDObject ) prestadoresCombo.getSelectedItem();
		boolean filtrar = true;
		Integer prestadorID = null;
		if( PRESTADOR_TODOS.equals( prestador ) )
		{
			filtrar = false;
		}
		else if( !PRESTADOR_SIPRP.equals( prestador ) )
		{
			prestadorID = prestador.getID();
		}
		try
		{
			Date data = dataPanel.getDate();
			Object ecdsArray[][] = provider.getListaECDsByData( data );
			List<Presenca> ecds = new Vector<Presenca>();
			for( int n = 0; n < ecdsArray.length; n++ )
			{
				Integer id = ( Integer ) ecdsArray[ n ][ 0 ];
				String nome = ( String ) ecdsArray[ n ][ 1 ];
				String nomePlain = ( String ) ecdsArray[ n ][ 2 ];
				String empresa = ( String ) ecdsArray[ n ][ 3 ];
				int tipo = ( ( Integer )ecdsArray[ n ][ 4 ] ).intValue();
				Integer prestadorMarcacao = ( Integer )ecdsArray[ n ][ 5 ];
				if( ( !filtrar ) || 
						( prestadorID == null ? prestadorMarcacao == null : prestadorID.equals( prestadorMarcacao ) ) )
				{
					ecds.add( new Presenca( id, nome, nomePlain, empresa, tipo ) );
				}
			}
			Collections.sort( ecds );
			ECDS = ecds.toArray( new Presenca[ ecds.size() ] );
			listECDsPanel.showList( ECDS );
			listECDsScroll.setViewportView( listECDsPanel );
			
			Object consultasArray[][] = provider.getListaConsultasByData( data );
			List<Presenca> consultas = new Vector<Presenca>();
			for( int n = 0; n < consultasArray.length; n++ )
			{
				Integer id = ( Integer ) consultasArray[ n ][ 0 ];
				String nome = ( String ) consultasArray[ n ][ 1 ];
				String nomePlain = ( String ) consultasArray[ n ][ 2 ];
				String empresa = ( String ) consultasArray[ n ][ 3 ];
				int tipo = ( ( Integer )consultasArray[ n ][ 4 ] ).intValue();
				Integer prestadorMarcacao = ( Integer )consultasArray[ n ][ 5 ];
				if( ( !filtrar ) || 
						( prestadorID == null ? prestadorMarcacao == null : prestadorID.equals( prestadorMarcacao ) ) )
				{
					consultas.add( new Presenca( id, nome, nomePlain, empresa, tipo ) );
				}
			}
			Collections.sort( consultas );
			listConsultasPanel.showList( consultas.toArray( new Presenca[ ecds.size() ] ) );
			listConsultasScroll.setViewportView( listConsultasPanel );
//			setExtendedState( getExtendedState() | MAXIMIZED_BOTH );
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a carregar dados", true );
		}
	}
	
	protected void recarregarPrestadores()
	{
		try
		{
			IDObject prestadores[] = prestadoresProvider.getPrestadoresActivos();
			prestadoresCombo.removeAllItems();
			prestadoresCombo.addItem( PRESTADOR_SIPRP );
			prestadoresCombo.addItem( PRESTADOR_TODOS );
			for( int n = 0; n < prestadores.length; n++ )
			{
				prestadoresCombo.addItem( prestadores[ n ] );
			}
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a carregar prestadores", true );
		}
	}
	
	protected void imprimirAuxiliares()
	{
		try
		{
			Date data = dataPanel.getDate();
			if( ECDS == null || data == null || ECDS.length == 0 )
			{
				return;
			}
			ClientesDataProvider clientesProvider = 
				( ClientesDataProvider ) ClientesDataProvider.getProvider();
			MedicinaDataProvider medicinaProvider = 
				( MedicinaDataProvider ) MedicinaDataProvider.getProvider();
			
			String dataStr = D_F.format( data );
			
			Element rootElement = new Element( "lista-presencas" );

			for( int n = 0; n < ECDS.length; n++ )
			{
				Element presencaElement = new Element( "presenca" );
				
				Element trabalhadorElement = new Element( "trabalhador" );
				trabalhadorElement.setText( ECDS[ n ].getNome() );
				presencaElement.addContent( trabalhadorElement );
				
				Element empresaElement = new Element( "empresa" );
				empresaElement.setText( ECDS[ n ].getNomeEmpresa() );
				presencaElement.addContent( empresaElement );
				
				Element dataElement = new Element( "data" );
				dataElement.setText( dataStr );
				presencaElement.addContent( dataElement );
				
				Integer trabalhadorID = medicinaProvider.getTrabalhadorIDByMarcacaoID( ECDS[ n ].getID() );
				Integer empresaID = clientesProvider.getEmpresaIDByTrabalhadorID( trabalhadorID );
				Integer realizados[] = medicinaProvider.getDetalhesRealizadosForEstadosMarcacao( ECDS[ n ].getID() );
				Vector realizadosVector = new Vector();
				realizadosVector.addAll( Arrays.asList( realizados ) );
				IDObject validos[] = medicinaProvider.getDetalhesValidosTrabalhador( empresaID, trabalhadorID );
				for( int v = 0; v < validos.length; v++ )
				{
					Integer id = validos[ v ].getID();
					if( !realizadosVector.contains( id ) )
					{
						Element ecdElement = new Element( "ecd" );
						ecdElement.setText( validos[ v ].toString() );
						presencaElement.addContent( ecdElement );
					}
				}
				
				rootElement.addContent( presencaElement );
			}

			Document doc = new Document( rootElement );

			ByteArrayOutputStream baos = new ByteArrayOutputStream();
	//new XMLOutputter().output( doc, System.out );
			new XMLOutputter().output( doc, baos );
			ByteArrayOutputStream out = new ByteArrayOutputStream();
			FOPCreator creator = FOPCreator.getFOPCreator();
			InputStream xmlIn = new ByteArrayInputStream( baos.toByteArray() );
			creator.createFOfromXML( xmlIn,
								getClass().getResourceAsStream( PRINT_TEMPLATE ), 
									out );
			ByteArrayInputStream in = new ByteArrayInputStream( out.toByteArray() );
			Hashtable printOptions = new Hashtable();
			FOPPrinter.getFOPPrinter().printFO( in, true, true, printOptions );
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a imprimir", true );
		}
	}
}
