/*
 * ImpressaoFichasUpperPanel.java
 *
 * Created on 19 de Fevereiro de 2006, 19:00
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package siprp.impressaofichas;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.print.*;
import javax.swing.*;
import javax.swing.event.*;
import java.util.*;

import com.evolute.utils.properties.*;
import com.evolute.utils.tables.*;
import com.evolute.utils.ui.*;
import com.evolute.utils.ui.calendar.*;
import com.evolute.utils.ui.window.*;

/**
 *
 * @author Frederico
 */
public class ImpressaoFichasWindow extends EditorWindow
	implements ListSelectionListener, ActionListener
{
	public final static String TITLE = "Impress\u00e3o de Fichas de Aptid\u00e3o";
	
	protected final static String PATH_PROPERTY_SUFFIX = ".path";
	
	private final static int iPermissionArray[][] =
		new int[][]{ {} };
	
	protected JCalendarPanel dataInicioPanel;
	protected JCalendarPanel dataFimPanel;
	protected VectorTableModel empresasModel;
	protected BaseTable empresasTable;
	protected VectorTableModel estabelecimentosModel;
	protected BaseTable estabelecimentosTable;
	protected VectorTableModel fichasModel;
	protected BaseTable fichasTable;
	protected JButton procurarButton;
	protected JTextField pathText;
	protected JButton pathButton;
	protected JComboBox impressorasCombo;
	protected JButton imprimirButton;
	protected JButton imprimirTodasButton;
	
	protected ImpressaoFichasDataProvider provider;
	protected PropertyHandler propertyHandler;
	
	/** Creates a new instance of ImpressaoFichasUpperPanel */
	public ImpressaoFichasWindow()
		throws Exception
	{
		super( iPermissionArray );
		provider = ( ImpressaoFichasDataProvider ) ImpressaoFichasDataProvider.getProvider();
		propertyHandler = new PropertyHandler();
		setupComponents();
	}
	
	private void setupComponents()
		throws Exception
	{
		setTitle( TITLE );
		empresasModel = new VectorTableModel( new String[]{ "empresas" } );
		empresasTable = new BaseTable( empresasModel );
		empresasTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
		empresasTable.setNonResizableNorReordable();
		JScrollPane empresasScroll = 
				new JScrollPane( empresasTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
									JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		empresasTable.getSelectionModel().addListSelectionListener( this );
		estabelecimentosModel = new VectorTableModel( new String[]{ "estabelecimentos" } );
		estabelecimentosTable = new BaseTable( estabelecimentosModel );
		estabelecimentosTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
		estabelecimentosTable.setNonResizableNorReordable();
		JScrollPane estabelecimentosScroll = 
				new JScrollPane( estabelecimentosTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
									JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		estabelecimentosTable.getSelectionModel().addListSelectionListener( this );
		fichasModel = new VectorTableModel( new String[]{ "trabalhador", "data" } );
		fichasTable = new BaseTable( fichasModel );
		fichasTable.fixColumnWidth( 1, 120 );
		fichasTable.setNonResizableNorReordable();
		fichasTable.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION );
		fichasTable.getSelectionModel().addListSelectionListener( this );
		JScrollPane fichasScroll = new JScrollPane( fichasTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,
													JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		JLabel inicioLabel = new JLabel( "In\u00edcio" );
		dataInicioPanel = new JCalendarPanel( null );
		JLabel fimLabel = new JLabel( "Fim" );
		dataFimPanel = new JCalendarPanel( null );
		procurarButton = new JButton( "Carregar" );
		procurarButton.addActionListener( this );
		procurarButton.setEnabled( false );
		pathText = new JTextField();
		pathText.setEditable( false );
		pathButton = new JButton( "Escolher Direct\u00f3rio" );
		pathButton.addActionListener( this );
		impressorasCombo = new JComboBox();
		PrintService printers[] = PrintServiceLookup.lookupPrintServices( null, null );
		for( int n = 0; n < printers.length; n++ )
		{
			impressorasCombo.addItem( printers[ n ].getName() );
		}
		imprimirButton = new JButton( "Imprimir escolhidas" );
		imprimirButton.addActionListener( this );
		imprimirButton.setEnabled( false );
		imprimirTodasButton = new JButton( "Imprimir Todas" );
		imprimirTodasButton.addActionListener( this );
		imprimirTodasButton.setEnabled( false );
		JPanel upperPad = new JPanel();
		JPanel lowerPad = new JPanel();
		JPanel upperPanel = new JPanel();
		
		GridBagLayout gridbag = new GridBagLayout();
		setLayout( gridbag );
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.insets = new Insets( 1, 1, 1, 1 );
		constraints.fill = GridBagConstraints.BOTH;
		constraints.gridheight = 1;
		constraints.weighty = 0.35;
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( upperPanel, constraints );
		
		constraints.gridwidth = 2;
		constraints.weightx = 1;
		constraints.weighty = 0.65;
		constraints.gridheight = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( fichasScroll, constraints );
		
		constraints.weighty = 0;
		constraints.gridheight = 1;
		constraints.weightx = 0;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( inicioLabel, constraints );
		gridbag.setConstraints( dataInicioPanel, constraints );
		gridbag.setConstraints( fimLabel, constraints );
		gridbag.setConstraints( dataFimPanel, constraints );
		gridbag.setConstraints( procurarButton, constraints );
		gridbag.setConstraints( pathText, constraints );
		gridbag.setConstraints( pathButton, constraints );
		gridbag.setConstraints( impressorasCombo, constraints );
		gridbag.setConstraints( imprimirButton, constraints );
		gridbag.setConstraints( imprimirTodasButton, constraints );
		
		constraints.weighty = 0.32;
		gridbag.setConstraints( upperPad, constraints );
		gridbag.setConstraints( lowerPad, constraints );
		
		add( upperPanel );
		add( fichasScroll );
		add( upperPad );
		add( inicioLabel );
		add( dataInicioPanel );
		add( fimLabel );
		add( dataFimPanel );
		add( procurarButton );
		add( lowerPad );
		add( pathButton );
		add( pathText );
		add( impressorasCombo );
		add( imprimirButton );
		add( imprimirTodasButton );
		
		upperPanel.setLayout( new GridLayout( 1, 2 ) );
		upperPanel.add( empresasScroll );
		upperPanel.add( estabelecimentosScroll );
		ColumnizedMappable empresas[] = provider.getAllEmpresas();
		Vector values = empresasModel.getValues();
		values.addAll( Arrays.asList( empresas ) );
		empresasModel.setValues( values );
		
		Properties properties = propertyHandler.load();
System.out.println( properties );
		String path = (String) properties.get( getClass().getName() + PATH_PROPERTY_SUFFIX );
		if( path == null )
		{
			setDirectorio( System.getProperty( "user.home" ) );
		}
		else
		{
			pathText.setText( path );
		}
	}
	
	public void valueChanged( ListSelectionEvent e )
	{
		Object source = e.getSource();
		if( e.getValueIsAdjusting() )
		{
			return;
		}
		if( source.equals( empresasTable.getSelectionModel() ) )
		{
			carregarEstabelecimentos();
		}
		else if( source.equals( estabelecimentosTable.getSelectionModel() ) )
		{
			procurarButton.setEnabled( estabelecimentosTable.getSelectedRow() != -1 );
		}
		else if( source.equals( fichasTable.getSelectionModel() ) )
		{
			imprimirButton.setEnabled( fichasTable.getSelectedRow() != -1 );
		}
	}
	
	protected void carregarEstabelecimentos()
	{
		estabelecimentosTable.clearSelection();
		int selected = empresasTable.getSelectedRow();
		estabelecimentosModel.clearAll();
		if( selected > -1 )
		{
			try
			{
				Integer empresaID = ( ( ColumnizedMappable ) empresasModel.getRowAt( selected ) ).getID();
				ColumnizedMappable estabelecimentos[] = provider.getAllEstabelecimentosForEmpresa( empresaID);
				Vector values = estabelecimentosModel.getValues();
				values.addAll( Arrays.asList( estabelecimentos ) );
				estabelecimentosModel.setValues( values );
			}
			catch( Exception ex )
			{
				DialogException.showExceptionMessage( ex, "Erro a carregar os estabelecimentos.", true );
				estabelecimentosModel.clearAll();
			}
		}
	}
	
	public void clear()
	{
		empresasTable.clearSelection();
	}
	
	public void fill( Object value )
	{
		if( value == null )
		{
			clear();
		}
		Integer ids[] = ( Integer [] ) value;
		for( int n = 0; n < empresasTable.getRowCount(); n++ )
		{
			if( ( ( ColumnizedMappable ) empresasModel.getRowAt( n ) ).getID().equals( ids[ 0 ] ) )
			{
				empresasTable.setRowSelectionInterval( n, n );
				break;
			}
		}
		
		for( int n = 0; n < estabelecimentosTable.getRowCount(); n++ )
		{
			if( ( ( ColumnizedMappable ) estabelecimentosModel.getRowAt( n ) ).getID().equals( ids[ 1 ] ) )
			{
				estabelecimentosTable.setRowSelectionInterval( n, n );
				break;
			}
		}
	}
	
	public Object save()
	{
		int empresaSelected = empresasTable.getSelectedRow();
		int estabelecimentoSelected = estabelecimentosTable.getSelectedRow();
		return new Integer[]{
				empresaSelected == -1 ? null : ( ( ColumnizedMappable ) empresasModel.getRowAt( empresaSelected ) ).getID(),
				estabelecimentoSelected == -1 ? null : ( ( ColumnizedMappable ) estabelecimentosModel.getRowAt( estabelecimentoSelected ) ).getID()
			};
	}
	
	public void setEnabled( boolean enable )
	{
		empresasTable.setEnabled( enable );
		estabelecimentosTable.setEnabled( enable );
	}
	
	public void actionPerformed( ActionEvent e )
	{
		Object source = e.getSource();
		if( source.equals( procurarButton ) )
		{
			procurar();
		}
		else if( source.equals( imprimirButton ) )
		{
			imprimir();
		}
		else if( source.equals( imprimirTodasButton ) )
		{
			imprimirTodas();
		}
		else if( source.equals( pathButton ) )
		{
			escolherDirectorio();
		}
	}
	
	public void procurar()
	{
		int selected = estabelecimentosTable.getSelectedRow();
		Date dataInicio = dataInicioPanel.getDate();
		Date dataFim = dataFimPanel.getDate();
		if( selected == -1 || ( dataInicio == null && dataFim == null ) )
		{
			JOptionPane.showMessageDialog( this, "Tem de escolher pelo menos uma data e um estabelecimento.", "Erro",
											JOptionPane.ERROR_MESSAGE );
			return;
		}
		if( dataInicio == null )
		{
			dataInicio = dataFim;
		}
		else if( dataFim == null )
		{
			dataFim = dataInicio;
		}
		fichasModel.clearAll();
		try
		{
			Integer estabelecimentoID = ( ( ColumnizedMappable ) estabelecimentosModel.getRowAt( selected ) ).getID();
			Object fichas[][] = provider.getAllFichasForEstabelecimentoAndDatas( estabelecimentoID, dataInicio, dataFim );
			Vector values = fichasModel.getValues();
			for( int n  = 0; n < fichas.length; n++ )
			{
				values.add( new ColumnizedObjectArray( fichas[ n ], true ) );
			}
			fichasModel.setValues( values );
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a carregar a lista.", true );
			estabelecimentosModel.clearAll();
		}
		imprimirTodasButton.setEnabled( fichasTable.getRowCount() > 0 );
	}
	
	public void imprimir()
	{
		imprimirLinhas( fichasTable.getSelectedRows() );
	}
	
	public void imprimirTodas()
	{
		int linhas[] = new int[ fichasTable.getRowCount() ];
		for( int n = 0; n < linhas.length; n++ )
		{
			linhas[ n ] = n;
		}
		imprimirLinhas( linhas );
	}
	
	protected void imprimirLinhas( int linhas[] )
	{
		try
		{
			File file = new File( pathText.getText().trim() );
			if( !file.exists() || !file.isDirectory() )
			{
				throw new IOException( "Direct\u00f3rio inexistente ou indispon\u00edvel: " + pathText.getText().trim() );
			}
		}
		catch( IOException ioex )
		{
			JOptionPane.showMessageDialog( this, ioex.getMessage(), "Erro...", 
												JOptionPane.ERROR_MESSAGE );
			return;
		}
		String impressora = ( String ) impressorasCombo.getSelectedItem();
		Integer ids[] = new Integer[ linhas.length ];
		for( int n = 0; n < ids.length; n++ )
		{
			ids[ n ] = ( ( ColumnizedObjectArray )fichasModel.getRowAt( linhas[ n ] ) ).getID();
		}
		int option = JOptionPane.showConfirmDialog( this, "Imprimir as " + ids.length + " fichas para a impressora " + impressora + "?",
										"Imprimir", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE );
		if( option == 0 )
		{
			System.out.println( "imprimir" );
			new FichasPrinter( ids, impressora, pathText.getText().trim(), 
								empresasModel.getRowAt( empresasTable.getSelectedRow() ).toString(), 
								estabelecimentosModel.getRowAt( estabelecimentosTable.getSelectedRow() ).toString() ).start();
		}
	}
	
	protected void escolherDirectorio()
	{
		JFileChooser chooser = new JFileChooser();
		chooser.setFileSelectionMode( JFileChooser.DIRECTORIES_ONLY );
		int returnVal = chooser.showOpenDialog( this );
		if(returnVal == JFileChooser.APPROVE_OPTION)
		{
			setDirectorio( chooser.getSelectedFile().getAbsolutePath() );
		}
	}
	
	protected void setDirectorio( String path )
	{
		if( path != null )
		{
			pathText.setText( path );
			Properties properties = propertyHandler.load();
			properties.setProperty( getClass().getName() + PATH_PROPERTY_SUFFIX, path );
			try
			{
				propertyHandler.save( properties );
			}
			catch( IOException ioex )
			{
				ioex.printStackTrace();
			}
		}
	}
}
