/*
 * EstabelecimentoPanel.java
 *
 * Created on 14 de Maio de 2004, 12:21
 */

package siprp.clientes;

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

import com.evolute.utils.*;
import com.evolute.utils.data.*;
import com.evolute.utils.dataui.*;
import com.evolute.utils.documents.*;
import com.evolute.utils.jdo.*;
import com.evolute.utils.tables.*;
import com.evolute.utils.ui.*;
import com.evolute.utils.ui.text.*;

import siprp.*;
import siprp.data.*;
/**
 *
 * @author  fpalma
 */
public class EstabelecimentoPanel extends JPanel
	implements ControllableComponent, ListSelectionListener, ActionListener
{
	public static int disables = 0;
	
	private JDOProvider JDO;
	
	private EstabelecimentoData estabelecimento;
	private ComponentsHashtable components;
	
	private EmpresaData empresa;
	
	private JTable estabelecimentosTable;	
	private JPanel toolbarPanel;
	
	private JTextField designacaoText;
	private JTextField moradaText;
	private JTextField localText;
	private JTextField codigoPostalText;
	private ContactoPanel contactoPanel;
	private JTextArea historicoText;
	private JButton marcacoesButton;
	
	private JPanel historicoPanel;
	private JPanel listaHistoricoPanel;
	private BaseTable historicoTable;
	private HistoricoEstabelecimentoPanel edicaoHistoricoPanel;
	private CardLayout historicoCardLayout;
		
//	private MarcacaoPanel marcacaoPanel;
	private SIPRPTracker tracker;
	
	private boolean lastEnable = false;

	/** Creates a new instance of EstabelecimentoPanel */
	public EstabelecimentoPanel( JPanel toolbarPanel, JTextField designacaoText, JTable estabelecimentosTable )
	{
		this.toolbarPanel = toolbarPanel;
		this.designacaoText = designacaoText;
		this.estabelecimentosTable = estabelecimentosTable;
		JDO = ( JDOProvider ) Singleton.getInstance( Singleton.DEFAULT_JDO_PROVIDER );
		setupComponents();
		setupComponentsHashtable();
	}
	
	private void setupComponents()
	{
		JPanel dadosEstabelecimentoPanel = new JPanel();
		JLabel designacaoLabel = new JLabel( "Designa\u00e7\u00e3o" );
		//designacaoText = new JTextField();
		JLabel moradaLabel = new JLabel( "Morada" );
		moradaText = new JTextField();
		JLabel codigoPostalLabel = new JLabel( "C\u00f3digo Postal" );
		codigoPostalText = new JTextField();
		codigoPostalText.setDocument( new MaximumLengthDocument( 8 ) );
		JLabel localLabel = new JLabel( "Local" );
		localText = new JTextField();
		contactoPanel = new ContactoPanel();
		contactoPanel.setBorder( BorderFactory.createTitledBorder( 
									BorderFactory.createEtchedBorder(),
									"Contacto" ) );
		marcacoesButton = new JButton( "Marca\u00e7\u00f5es" );
		marcacoesButton.addActionListener( this );
		JPanel pad;
		historicoText = new JTextArea();
		new CopyPasteHandler( historicoText );
		historicoText.setLineWrap( true );
		historicoText.setWrapStyleWord( true );
		JScrollPane observacoesScp = new JScrollPane( historicoText, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
													JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		observacoesScp.setBorder( BorderFactory.createTitledBorder( 
									BorderFactory.createEtchedBorder(), "Observa\u00e7\u00f5es" ) );
		historicoPanel = new JPanel();
		historicoPanel.setBorder( BorderFactory.createTitledBorder( 
									BorderFactory.createEtchedBorder(), "Hist\u00f3rico" ) );
//		marcacaoPanel = new MarcacaoPanel( true, "Realizada", "Relat\u00f3rio", Marcacao.TIPO_MARCACAO_ESTABELECIMENTO );
//		marcacaoPanel.setCalendarDialogOrientation( JCalendarDialog.ABOVE, JCalendarDialog.LEFT );
//		marcacaoPanel.setBorder( BorderFactory.createTitledBorder( 
//									BorderFactory.createEtchedBorder(),
//									"Visita" ) );
		
		GridBagLayout gridbag = new GridBagLayout();
		dadosEstabelecimentoPanel.setLayout( gridbag );
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.insets = new Insets( 1, 1, 1, 1 );
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.gridheight = 1;
		constraints.weighty = 0;
		
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( toolbarPanel, constraints );
		dadosEstabelecimentoPanel.add( toolbarPanel );
		
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.weighty = 1;
		pad = new JPanel();
		gridbag.setConstraints( pad, constraints );
		dadosEstabelecimentoPanel.add( pad );
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.weighty = 0;
		
		constraints.weightx = 0;
		constraints.gridwidth = 1;
		gridbag.setConstraints( moradaLabel, constraints );
		dadosEstabelecimentoPanel.add( moradaLabel );
		
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( moradaText, constraints );
		dadosEstabelecimentoPanel.add( moradaText );
		
		constraints.weightx = 0;
		constraints.gridwidth = 1;
		gridbag.setConstraints( codigoPostalLabel, constraints );
		dadosEstabelecimentoPanel.add( codigoPostalLabel );
		
		constraints.weightx = 0.3;
		constraints.gridwidth = 1;
		gridbag.setConstraints( codigoPostalText, constraints );
		dadosEstabelecimentoPanel.add( codigoPostalText );
		
		constraints.weightx = 0.7;
		constraints.gridwidth = GridBagConstraints.REMAINDER;		
		pad = new JPanel();
		gridbag.setConstraints( pad, constraints );
		dadosEstabelecimentoPanel.add( pad );
		
		constraints.weightx = 0;
		constraints.gridwidth = 1;
		gridbag.setConstraints( localLabel, constraints );
		dadosEstabelecimentoPanel.add( localLabel );
		
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( localText, constraints );
		dadosEstabelecimentoPanel.add( localText );
		
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( marcacoesButton, constraints );
		dadosEstabelecimentoPanel.add( marcacoesButton );
		
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( contactoPanel, constraints );
		
		gridbag = new GridBagLayout();
		setLayout( gridbag );
		constraints.fill = GridBagConstraints.BOTH;
		constraints.weighty = 0;
		constraints.gridheight = 1;
		constraints.weightx = 0.5;
		constraints.gridwidth = 1;
		gridbag.setConstraints( dadosEstabelecimentoPanel, constraints );
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( contactoPanel, constraints );
		constraints.weightx = 0.5;
		constraints.weighty = 1;
		constraints.gridwidth = 1;
		constraints.gridheight = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( historicoPanel, constraints );
		constraints.weightx = 0.5;
		constraints.weighty = 1;
		constraints.gridheight = GridBagConstraints.REMAINDER;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( observacoesScp, constraints );
		add( dadosEstabelecimentoPanel );
		add( contactoPanel );
		add( historicoPanel );
		add( observacoesScp );
		
		listaHistoricoPanel = new JPanel();
		listaHistoricoPanel.setLayout( new GridLayout( 1, 1 ) );
		VectorTableModel marcacoesModel = new VectorTableModel( new String[]{ "Data", "Texto" } );
		historicoTable = new BaseTable( marcacoesModel );
		historicoTable.setToolTipColumn( 1 );
		historicoTable.fixColumnWidth( 0, 150 );
		historicoTable.setNonResizableNorReordable();
		JScrollPane listaHistoricoScp = new JScrollPane( historicoTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED, 
													JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		listaHistoricoPanel.add( listaHistoricoScp );
		
		historicoCardLayout = new CardLayout();
		edicaoHistoricoPanel = new HistoricoEstabelecimentoPanel( this );
		historicoPanel.setLayout( historicoCardLayout );
		historicoPanel.add( HistoricoEstabelecimentoPanel.LIST_PANEL, listaHistoricoPanel );
		historicoPanel.add( HistoricoEstabelecimentoPanel.EDIT_PANEL, edicaoHistoricoPanel );
		
		historicoTable.getSelectionModel().addListSelectionListener( new ListSelectionListener(){
			public void valueChanged( ListSelectionEvent e )
			{
				int selected = historicoTable.getSelectedRow();
				if( selected == -1 || e.getValueIsAdjusting() )
				{
					return;
				}
				Object row = ( (VectorTableModel)historicoTable.getModel() ).getRowAt( selected );
				historicoTable.clearSelection();
				edicaoHistoricoPanel.setEstabelecimento( estabelecimento );
				if( row != null && row instanceof HistoricoEstabelecimentoData )
				{
					edicaoHistoricoPanel.fill( row );
				}
				else
				{
					edicaoHistoricoPanel.fill( null );
				}
				historicoCardLayout.show( historicoPanel, HistoricoEstabelecimentoPanel.EDIT_PANEL );
			}
		} );
		
		new CopyPasteHandler( designacaoText );
		new CopyPasteHandler( moradaText );
		new CopyPasteHandler( localText );
		new CopyPasteHandler( codigoPostalText );
	}
	
	private void setupComponentsHashtable()
	{
		components = new ComponentsHashtable();
		components.putComponent( EstabelecimentoData.NOME, designacaoText );
		components.putComponent( EstabelecimentoData.MORADA, moradaText );
		components.putComponent( EstabelecimentoData.LOCALIDADE, localText );
		components.putComponent( EstabelecimentoData.CODIGO_POSTAL, codigoPostalText );
		components.putComponent( EstabelecimentoData.CONTACTO, contactoPanel );
//		components.putComponent( EstabelecimentoData.HISTORICO, historicoText );
		components.putComponent( EstabelecimentoData.HISTORICO, historicoText );
		components.putDummy( EstabelecimentoData.EMPRESA );
		components.putDummy( EstabelecimentoData.NOME_PLAIN );
//		components.putDummy( EstabelecimentoData.INACTIVO );
	}
	
	public void clear()
	{
		String names[] = (String[])components.keySet().toArray( new String[0] );
		ComponentController.clear( names, components );
		clearHistorico();
		estabelecimento = null;
	}
	
	public void fill(Object value)
	{
		clear();
		estabelecimento = ( EstabelecimentoData ) value;
//		marcacaoPanel.setEnabled( estabelecimento != null );
//		marcacaoPanel.fill( estabelecimento );
		if( estabelecimento == null )
		{
			estabelecimentosTable.clearSelection();
			return;
		}
		String names[] = estabelecimento.getFieldNames();
		ComponentController.fill( names, estabelecimento.getHashData(), components );
		reloadHistorico();
	}
	
	public Object save()
	{
		if( estabelecimento == null )
		{
			estabelecimento = new EstabelecimentoData();
		}
			
		String names[] = estabelecimento.getFieldNames();
		Hashtable hash = new Hashtable();
		ComponentController.save( names, hash, components );
		estabelecimento.setHashData( hash );
		estabelecimento.set( EstabelecimentoData.EMPRESA, empresa );
		return estabelecimento;
	}
	
	public void postSave()
	{
		int selected = estabelecimentosTable.getSelectedRow();
		if( estabelecimento != null )
		{
			IDObject obj = new MappableObject( (Integer) estabelecimento.get( EstabelecimentoData.ID ), estabelecimento.get( EstabelecimentoData.NOME ) );
			VectorTableModel model = (VectorTableModel)estabelecimentosTable.getModel();
			if( selected == -1 )
			{
				model.insertRowAt( obj, estabelecimentosTable.getRowCount() );
				estabelecimentosTable.setRowSelectionInterval( estabelecimentosTable.getRowCount() - 1, estabelecimentosTable.getRowCount() - 1 );
			}
			else
			{
				model.removeRowAt( selected );
				model.insertRowAt( obj, selected );
				estabelecimentosTable.setRowSelectionInterval( selected, selected );
			}
		}
	}
	
	public void setEnabled( boolean enable )
	{
		super.setEnabled( enable );
		String names[] = (String[])components.keySet().toArray( new String[0] );
		ComponentController.setEnabled( names, enable, components );
		if( enable != lastEnable )
		{
			if( enable )
			{
				disables++;
			}
			else
			{
				disables--; 
			}
			lastEnable = enable;
		}
		estabelecimentosTable.setEnabled( disables == 0 );
//		if( estabelecimento == null )
//		{
//			marcacaoPanel.setEnabled( false );
//		}
	}
	
	public void valueChanged( ListSelectionEvent e )
	{
		Object source = e.getSource();
		if( source instanceof EmpresaPanel )
		{
			Integer id = ( ( EmpresaPanel ) source ).getSelectedEstabelecimento();
			if( id != null )
			{
				try
				{
					EstabelecimentoData estab = ( EstabelecimentoData ) JDO.load( EstabelecimentoData.class, id );
					fill( estab );
				}
				catch( Exception ex )
				{
					DialogException.showExceptionMessage( ex, "Erro a carregar o estabelecimento", true );
					clear();
				}
			}
			else
			{
				clear();
			}
		}
	}
	
	public void reload()
	{
		fill( estabelecimento );
	}
	
	public void setEmpresa( EmpresaData empresa )
	{
		this.empresa = empresa;
	}
	
	protected void reloadHistorico()
	{
		try
		{
			Collection historicoCollection =
				JDO.listLoad( HistoricoEstabelecimento.class, new Object[]{ estabelecimento.get( EstabelecimentoData.ID ) },
								new String []{ "estabelecimento.id" }, new String[]{ "data descending" } );
			Vector historico = new Vector();
			historico.add( new ColumnizedObject(){
				public Object getValue( int col )
				{
					switch( col )
					{
						case 0:
							return "";
						case 1:
							return "NOVO EVENTO...";
					}
					return null;
				}
			} );
			if( historicoCollection != null )
			{
				historico.addAll( historicoCollection );
			}
			historicoTable.clearSelection();
			( (VectorTableModel) historicoTable.getModel() ).setValues( historico );
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a carregar as Marca\u00e7\u00f5es", true );
		}
		showHistorico();
	}
	
	protected void showHistorico()
	{
		historicoCardLayout.show( historicoPanel, HistoricoEstabelecimentoPanel.LIST_PANEL );
	}
	
	protected void clearHistorico()
	{
		( (VectorTableModel) historicoTable.getModel() ).clearAll();
	}
	
	public void actionPerformed( ActionEvent e )
	{
		Object source = e.getSource();
		if( source.equals( marcacoesButton ) )
		{
			if( empresa == null || estabelecimento == null )
			{
				return;
			}
			else
			{
				tracker.getHigieneWindow().setVisible( true );
				tracker.getHigieneWindow().setEmpresaAndEstabelecimento( (Integer) empresa.get( EmpresaData.ID ),
																( Integer ) estabelecimento.get( EstabelecimentoData.ID ) );
			}
		}
	}
	
	public void setTracker( SIPRPTracker tracker )
	{
		this.tracker = tracker;
	}
}
