/*
 * UpperPanel.java
 *
 * Created on 29 de Marco de 2004, 17:44
 */

package siprp.ficha;

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

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

import siprp.*;
import siprp.data.*;

/**
 *
 * @author  fpalma
 */
public class UpperPanel extends JPanel
	implements ControllableComponent, ItemListener
{
	protected JDOProvider JDO;
	
	protected JFrame owner;
	private JTextField empresaText;
	private JTextField nomeText;
	private JComboBox medicosCombo;
	private JTextField cpText;
	
	private FichaDataProvider provider;
	private Hashtable medicosHash;
	
	/** Creates a new instance of UpperPanel */
	public UpperPanel()
		throws Exception
	{
		provider = (FichaDataProvider)FichaDataProvider.getProvider();
		medicosHash = new Hashtable();
		JDO = ( JDOProvider ) Singleton.getInstance( Singleton.DEFAULT_JDO_PROVIDER );
		setupComponents();
	}
	
	private void setupComponents()
		throws Exception
	{
		JLabel empresaLabel = new JLabel( "Empresa/Entidade" );
		empresaText = new JTextField();
		empresaText.setEditable( false );
		JLabel nomeLabel = new JLabel( "Nome" );
		nomeText = new JTextField();
		nomeText.setEditable( false );
		JLabel medicoLabel = new JLabel( "M\u00e9dico" );
		medicosCombo = new JComboBox();
		JLabel cpLabel = new JLabel( "c.p." );
		cpText = new JTextField();
		cpText.setEditable( false );
		fillCombo();
		GridBagLayout gridbag = new GridBagLayout();
		setLayout( gridbag );
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.insets = new Insets( 0, 1, 0, 1 );
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.gridheight = 1;
		constraints.weighty = 0;
		
		constraints.gridwidth = 1;
		constraints.weightx = 0;
		gridbag.setConstraints( empresaLabel, constraints );
		add( empresaLabel );
		
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.weightx = 1;
		gridbag.setConstraints( empresaText, constraints );
		add( empresaText );
		
		constraints.gridwidth = 1;
		constraints.weightx = 0;
		gridbag.setConstraints( nomeLabel, constraints );
		add( nomeLabel );
		
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.weightx = 1;
		gridbag.setConstraints( nomeText, constraints );
		add( nomeText );
		
		constraints.gridwidth = 1;
		constraints.weightx = 0;
		gridbag.setConstraints( medicoLabel, constraints );
		add( medicoLabel );
		
		constraints.gridwidth = 1;
		constraints.weightx = 0.8;
		gridbag.setConstraints( medicosCombo, constraints );
		add( medicosCombo );
		
		constraints.gridwidth = 1;
		constraints.weightx = 0;
		gridbag.setConstraints( cpLabel, constraints );
		add( cpLabel );
		
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.weightx = 0.2;
		gridbag.setConstraints( cpText, constraints );
		add( cpText );
		
		new CopyPasteHandler( empresaText );
		new CopyPasteHandler( nomeText );
		new CopyPasteHandler( cpText );
	}
		
	public void fill(Object value)
	{
		Integer values[] = (Integer[])value;
		Integer empresaID = values[0];
		Integer estabelecimentoID = values[1];
		Integer trabalhadorID = values[2];
		clear();
		try
		{
			TrabalhadorData trabalhador;
			EstabelecimentoData estabelecimento;
			EmpresaData empresa;
			if( trabalhadorID != null  )
			{
				trabalhador = ( TrabalhadorData ) JDO.load( TrabalhadorData.class, trabalhadorID );
				String nome = (String) trabalhador.get( TrabalhadorData.NOME );
				nomeText.setText( nome );
			}
			String nomeEstabelecimento = "";
			if( estabelecimentoID != null )
			{
				estabelecimento = ( EstabelecimentoData ) JDO.load( EstabelecimentoData.class, estabelecimentoID );
				nomeEstabelecimento = (String) estabelecimento.get( EstabelecimentoData.NOME );
				try
				{
					Integer medicoID = provider.getMedicoForEstabelecimento( estabelecimentoID );
					if( medicoID != null && medicoID.intValue() > -1 )
					{
						for( int n = 0; n < medicosCombo.getItemCount(); n++ )
						{
							IDObject medico = ( IDObject ) medicosCombo.getItemAt( n );
							if( medico.getID().equals( medicoID ) )
							{
								medicosCombo.setSelectedIndex( n );
								break;
							}
						}
					}
				}
				catch( Exception ex )
				{
				}
			}
			if( empresaID != null )
			{
				empresa = ( EmpresaData ) JDO.load( EmpresaData.class, empresaID );
				String nomeEmpresa = (String) empresa.get( EmpresaData.DESIGNACAO_SOCIAL );
				empresaText.setText( nomeEmpresa + ( nomeEstabelecimento.length() > 0?" / " + nomeEstabelecimento:"" ) );
			}
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a carregar os dados do cabe\u00e7alho...", true );
		}
	}
	
	public Object save()
	{
		Integer id = ( (IDObject) medicosCombo.getSelectedItem() ).getID();
		if( id != null )
		{
			try
			{
				MedicoData medico = ( MedicoData )JDO.load( MedicoData.class, id );
				return medico;
			}
			catch( Exception ex )
			{
				ex.printStackTrace();
			}
		}
		else
		{
			throw new ValuesException( "A ficha tem de ter um m\u00e9dico associado" );
		}
		return null;
	}
	
	public void fillCombo()
		throws Exception
	{
		medicosCombo.removeItemListener( this );
		medicosCombo.removeAllItems();
		medicosHash.clear();
		Object medicos[][] = provider.getAllMedicos();
		for( int n = 0; n < medicos.length; n++ )
		{
			Object medico[] = new Object[ 4 ];
			medico[ 0 ] = new Integer( ( (Number)medicos[n][0] ).intValue() );
			medico[ 1 ] = medicos[ n ][ 1 ];
			medico[ 2 ] = medicos[ n ][ 2 ];
			medico[ 3 ] = new Integer( n );
			medicosHash.put( medicos[ n ][ 0 ], medico );
			medicosCombo.addItem( new MappableObject( (Integer) medico[ 0 ], medico[ 1 ] ) );
		}
		
		if( medicos.length > 0 )
		{
			medicosCombo.setSelectedIndex( 0 );
			cpText.setText( medicos[ 0 ][ 2 ] != null?(String)medicos[ 0 ][ 2 ]:"" );
		}
		else
		{
			medicosCombo.addItem( new MappableObject( null, "" ) );
			medicosCombo.setSelectedIndex( 0 );
			cpText.setText( "" );
		}
		medicosCombo.addItem( new MappableObject( new Integer( -1 ), "Novo/Editar" ) );
		medicosCombo.addItemListener( this );
	}
	
	public void itemStateChanged(java.awt.event.ItemEvent itemEvent)
	{
		int index = medicosCombo.getSelectedIndex();
		if( index == medicosCombo.getItemCount() - 1 )
		{
			try
			{
				MedicoEditor me = new MedicoEditor( owner );
				me.show();
//				boolean isNew = me.getIsNew();
				Integer id = me.getID();
				if( id == null )
				{
					medicosCombo.setSelectedIndex( 0 );
				}
				else
				{
					fillCombo();
					if( id != null )
					{
						Object[] medico = (Object[])medicosHash.get( id );
						medicosCombo.setSelectedIndex( ((Integer)medico[ 3 ] ).intValue() );
					}
				}
				
			}
			catch( Exception ex )
			{
				JOptionPane.showMessageDialog( null, "Erro a abrir a janela de edi\u00e7\u00e3o...", "Erro...",
					JOptionPane.ERROR_MESSAGE );
				ex.printStackTrace();
				medicosCombo.setSelectedIndex( 0 );
				return;
			}
		}
		else
		{
			IDObject selected = (IDObject)medicosCombo.getItemAt( index );
			Integer id = selected.getID();
			if( id == null )
			{
				cpText.setText( "" );
			}
			else
			{
				Object[] medico = (Object[])medicosHash.get( id );
				cpText.setText( medico[ 2 ] != null?(String)medico[ 2 ]:"" );
			}
		}
	}
	
	public void clear()
	{
		empresaText.setText( "" );
		nomeText.setText( "" );
		medicosCombo.setSelectedIndex( 0 );
	}
	
	public void setEnabled( boolean enable )
	{
		medicosCombo.setEnabled( enable );
	}
}
