/*
 * LembretesWindow.java
 *
 * Created on 13 de Fevereiro de 2007, 11:11
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package siprp.lembretes;

import info.clearthought.layout.TableLayout;
import info.clearthought.layout.TableLayoutConstraints;

import java.awt.*;
import java.awt.event.ActionEvent;
import javax.swing.*;

import com.evolute.utils.tables.*;
import com.evolute.utils.tables.special.ComboBoxData;
import com.evolute.utils.tracker.TrackableWindow;
import com.evolute.utils.ui.DialogException;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import java.util.Vector;

import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import siprp.database.cayenne.objects.Empresas;
import siprp.database.cayenne.objects.Estabelecimentos;
import siprp.database.cayenne.providers.MedicinaDAO;
import siprp.lembretes.externos.LembretesExternosPanel;
import siprp.lembretes.marcacoes.LembretesMarcacaoPanel;
import siprp.lembretes.remarcacoes.LembretesRemarcacaoPanel;

/**
 *
 * @author Frederico
 */
public class LembretesWindow extends JFrame
	implements ActionListener, TrackableWindow, ListSelectionListener,
				LembretesConstants
{
	public static final String TITLE = "Lembretes";
	
	private static final int LEFT_COLUMN_WIDTH = 302;
	
	protected VectorTableModel tiposModel;
	protected BaseTable tiposTable;
	protected JPanel lembretesPanel;
	protected JButton recarregarButton;
	
	private final JPanel leftPanel = new JPanel();
	private final JCheckBox checkEmpresas = new JCheckBox();
	private final JComboBox comboEmpresas = new JComboBox(  );
	private final JCheckBox checkEstabelecimentos = new JCheckBox();
	private final JComboBox comboEstabelecimentos = new JComboBox(  );
	
	private final MedicinaDAO medicinaDao = new MedicinaDAO();
	
	protected LembretesDataProvider provider;
	
	/** Creates a new instance of LembretesWindow */
	public LembretesWindow()
		throws Exception
	{
		provider = LembretesDataProvider.getProvider();
		setupComponents();
	}
	
	private void setupComponents()
	{
		setTitle( "Lembretes" );
		tiposModel = new VectorTableModel( new String[]{ "tipo", "quantidade" } );
		tiposTable = new BaseTable( tiposModel );
		tiposTable.setSelectionMode( ListSelectionModel.SINGLE_SELECTION );
		tiposTable.fixColumnWidth( 0, 200 );
		tiposTable.fixColumnWidth( 1, 100 );
		tiposTable.getSelectionModel().addListSelectionListener( this );
		JScrollPane scp =
			new JScrollPane( tiposTable, JScrollPane.VERTICAL_SCROLLBAR_NEVER,
			JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		scp.setPreferredSize( new Dimension( LEFT_COLUMN_WIDTH, 100 ) );
		lembretesPanel = new JPanel();
		lembretesPanel.setLayout( new GridLayout( 1, 1 ) );
		recarregarButton = new JButton( "Recarregar" );
		recarregarButton.addActionListener( this );
		
		loadEmpresas();
		loadEstabelecimentos();
		
		double[] cols = new double[]{ TableLayout.MINIMUM, TableLayout.FILL };
		double[] rows = new double[]{ TableLayout.PREFERRED, TableLayout.PREFERRED,
		                              TableLayout.MINIMUM, TableLayout.MINIMUM,
		                              TableLayout.MINIMUM, TableLayout.MINIMUM,
		                              TableLayout.MINIMUM
		                              };
		TableLayout tableLayout = new TableLayout( cols, rows );
		tableLayout.setHGap( 5 );
		tableLayout.setVGap( 5 );
		leftPanel.setPreferredSize( new Dimension( LEFT_COLUMN_WIDTH, 0 ) );
		leftPanel.setLayout( tableLayout );
		
		comboEmpresas.setPreferredSize( new Dimension( LEFT_COLUMN_WIDTH - 50, 0 ) );
		comboEstabelecimentos.setPreferredSize( new Dimension( LEFT_COLUMN_WIDTH - 50, 0 ) );
		checkEstabelecimentos.setEnabled( false );
		comboEstabelecimentos.setEnabled( false );
		
		leftPanel.add( scp, new TableLayoutConstraints(0,0,1,0) );
		leftPanel.add( new JSeparator(), new TableLayoutConstraints(0,1,1,1) );
		leftPanel.add( new JLabel( "Filtrar por:"), new TableLayoutConstraints(0,2,1,2) );
		leftPanel.add( checkEmpresas, new TableLayoutConstraints(0,3) );
		leftPanel.add( new JLabel( "Empresa"), new TableLayoutConstraints(1,3) );
		leftPanel.add( comboEmpresas, new TableLayoutConstraints(1,4) );
		leftPanel.add( checkEstabelecimentos, new TableLayoutConstraints(0,5) );
		leftPanel.add( new JLabel( "Estabelecimento"), new TableLayoutConstraints(1,5) );
		leftPanel.add( comboEstabelecimentos, new TableLayoutConstraints(1,6)  );
		
		cols = new double[]{ TableLayout.PREFERRED, TableLayout.FILL };
		rows = new double[]{ TableLayout.FILL, TableLayout.MINIMUM };
		tableLayout = new TableLayout( cols, rows );
		tableLayout.setHGap( 5 );
		tableLayout.setVGap( 5 );
//		getContentPane().setPreferredSize( new Dimension( 300, 20 ) );
		getContentPane().setLayout( tableLayout );
		
		getContentPane().setLayout( tableLayout );
		getContentPane().add( leftPanel, new TableLayoutConstraints( 0, 0 ) );
		getContentPane().add( lembretesPanel, new TableLayoutConstraints( 1, 0 ) );
		getContentPane().add( recarregarButton, new TableLayoutConstraints( 0, 1, 1, 1 ) );
		
		addWindowListener( new WindowAdapter(){
			public void windowClosing( WindowEvent e )
			{
				close();
			}
			
			public void windowOpened( WindowEvent e )
			{
//				setExtendedState( getExtendedState() | MAXIMIZED_BOTH );
				setSize( 1024, 700 );
				reloadTotais();
			}
		} );
		
		
		
		setupComboListeners();
		setupCheckBoxListeners();
		comboEmpresas.setEnabled( false );
		comboEstabelecimentos.setEnabled( false );
	}
	
	private void setupComboListeners()
	{
		comboEmpresas.addItemListener( new ItemListener()
		{
			@Override
			public void itemStateChanged( ItemEvent e )
			{
				if( e.getStateChange() == ItemEvent.SELECTED )
				{
					loadEstabelecimentos();
					if( checkEmpresas.isEnabled() && checkEmpresas.isEnabled() )
					{
						reloadLembretes();
					}
				}
			}
		} );
		comboEstabelecimentos.addItemListener( new ItemListener()
		{
			@Override
			public void itemStateChanged( ItemEvent e )
			{
				if( e.getStateChange() == ItemEvent.SELECTED && checkEstabelecimentos.isEnabled() )
				{
					reloadLembretes();
				}
			}
		} );
	}
	
	private void setupCheckBoxListeners()
	{
		checkEmpresas.addChangeListener( new ChangeListener()
		{
			@Override
			public void stateChanged( ChangeEvent e )
			{
				empresasChecked();
				reloadLembretes();
			}
		});
		checkEstabelecimentos.addChangeListener( new ChangeListener()
		{
			@Override
			public void stateChanged( ChangeEvent e )
			{
				reloadLembretes();
			}
		});
	}
	
	private void empresasChecked()
	{
		boolean filtrarEmpresas = checkEmpresas.isSelected();
		checkEstabelecimentos.setEnabled( filtrarEmpresas );
		comboEstabelecimentos.setEditable( filtrarEmpresas );
		comboEstabelecimentos.setEnabled( filtrarEmpresas );
		if( !filtrarEmpresas )
		{
			checkEstabelecimentos.setSelected( false );
		}
	}
	
	public void refresh()
	{
	}

	public void open()
	{
		setVisible( true );
	}
	
	public void close()
	{
		SwingUtilities.invokeLater( new Runnable() {
			public void run()
			{
				setVisible( false );
				dispose();
			}
		} );
	}
	
	protected void reloadTotais()
	{
		try
		{
			Vector values = tiposModel.getValues();
			values.clear();
			TipoLembrete tipos[] = provider.getTiposLembrete();
			for( int n = 0; n < tipos.length; n++ )
			{
				int count = provider.countLembretesByTipo( tipos[ n ].getID() );
				values.add( new ColumnizedObjectArray( 
					new Object[]{ tipos[ n ].getID(), tipos[ n ].getDescricao(),
									"" + count }, true ) );
			}
			tiposModel.setValues( values );
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a carregar lembretes", true );
		}
	}
	
	protected void reloadLembretes()
	{
		lembretesPanel.removeAll();
		int selected = tiposTable.getSelectedRow();
		if( selected != -1 )
		{
			ColumnizedObjectArray line = ( ColumnizedObjectArray ) tiposModel.getRowAt( selected );
			Integer tipoID = line.getID();
			Empresas empresa = (Empresas) comboEmpresas.getSelectedItem();
			Estabelecimentos estabelecimento = (Estabelecimentos) comboEstabelecimentos.getSelectedItem();
			Integer empresaID = ( empresa != null && checkEmpresas.isSelected() ) ? empresa.getId() : null;
			Integer estabelecimentoID = ( estabelecimento != null && checkEstabelecimentos.isSelected() ) ? estabelecimento.getId() : null;
			try
			{
				TipoLembrete tipo = provider.getTipoLembreteByID( tipoID );
				if( CODE_EXTERNO.equals( tipo.getCodigo() ) )
				{
					lembretesPanel.add( new LembretesExternosPanel( empresaID, estabelecimentoID ) );
				}
				if( CODE_REMARCACOES.equals( tipo.getCodigo() ) )
				{
					lembretesPanel.add( new LembretesRemarcacaoPanel( empresaID, estabelecimentoID ) );
				}
				if( CODE_MARCACOES.equals( tipo.getCodigo() ) )
				{
					lembretesPanel.add( new LembretesMarcacaoPanel( empresaID, estabelecimentoID ) );
				}
				if( CODE_OUTROS.equals( tipo.getCodigo() ) )
				{
				}
				
			}
			catch( Exception ex )
			{
				DialogException.showExceptionMessage( ex, "Erro a carregar lembretes", true );
			}
		}
		validate();
		repaint();
	}
	
	private void loadEmpresas()
	{
		comboEmpresas.removeAllItems();
		List<Empresas> allEmpresas = medicinaDao.getAllEmpresas();
		for( Empresas empresa : allEmpresas )
		{
			comboEmpresas.addItem( empresa );
		}
		
	}
	
	private void loadEstabelecimentos()
	{
		comboEstabelecimentos.removeAllItems();
		Object selectedEmpresa = comboEmpresas.getSelectedItem();
		if( selectedEmpresa != null )
		{
			if( selectedEmpresa instanceof Empresas )
			{
				List<Estabelecimentos> allEstabelecimentos = ((Empresas) selectedEmpresa).getEstabelecimentosArray();
				for( Estabelecimentos estabelecimento : allEstabelecimentos )
				{
					comboEstabelecimentos.addItem( estabelecimento );
				}
			}
		}
	}

	public boolean closeIfPossible()
	{
		close();
		return true;
	}

	public void actionPerformed(ActionEvent e)
	{
		Object source = e.getSource();
		if( source.equals( recarregarButton ) )
		{
			reloadTotais();
			loadEmpresas();
			loadEstabelecimentos();
		}
	}

	public void valueChanged(ListSelectionEvent e)
	{
		if( !e.getValueIsAdjusting() )
		{
			reloadLembretes();
			boolean selected = tiposTable.getSelectedRowCount() > 0;
			comboEmpresas.setEnabled( selected );
			comboEstabelecimentos.setEnabled( selected );
		}
	}
}
