/*
 * EmpresaPanel.java
 *
 * Created on 29 de Marco de 2004, 11:53
 */

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.button.*;
import com.evolute.utils.ui.panel.*;
import com.evolute.utils.ui.text.*;

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

/**
 *
 * @author  fpalma
 */
public class EmpresaPanel extends JPanel
	implements ControllableComponent
{
	private JDOProvider JDO;
	private JTextField designacaoSocialText;
	private JTextField estabelecimentoText;
	private JTextField localidadeText;
	private RadioButtonFixedPanel servicoSaudeTipoPanel;
	private JTextField designacaoServicoSaudeText;
	private JButton defaultServicoSaudeButton;
	private RadioButtonFixedPanel servicoHigieneTipoPanel;
	private JTextField designacaoText;
	private JButton defaultServicoHigieneButton;
	
	private FichaDataProvider provider;
	private ComponentsHashtable empresaComponents;
	private ComponentsHashtable estabelecimentoComponents;
	
	private EstabelecimentoData estabelecimento;
	private EmpresaData empresa;
	
	
	/** Creates a new instance of EmpresaPanel */
	public EmpresaPanel()
		throws Exception
	{
		provider = (FichaDataProvider)FichaDataProvider.getProvider();
		JDO = ( JDOProvider ) Singleton.getInstance( Singleton.DEFAULT_JDO_PROVIDER );
		setupComponents();
		setupComponentsHashtable();
	}
	
	private void setupComponents()
	{
		setBorder( BorderFactory.createTitledBorder(
					BorderFactory.createEtchedBorder(),
					"Empresa/Entidade" ) );
		
		JLabel designacaoSocialLabel = new JLabel( "Designa\u00e7\u00e3o Social" );
		designacaoSocialText = new JTextField();
//		JPanel servicoSaudePanel = new JPanel();
		JLabel estabelecimentoLabel = new JLabel( "Estabelecimento" );
		estabelecimentoText = new JTextField();
		JLabel localidadeLabel = new JLabel( "Localidade" );
		localidadeText = new JTextField();
		JLabel servicoSaudeLabel = new JLabel( "Servi\u00e7o de Sa\u00fade: Tipo" );
		servicoSaudeTipoPanel = 
			new RadioButtonFixedPanel( new IDObject[]{ new MappableObject( new Integer(1), "Interno" ), 
													new MappableObject( new Integer(2), "Interempresas" ),
													new MappableObject( new Integer(3), "Externo" ), 
													new MappableObject( new Integer(4), "Servi\u00e7o Nacional de Sa\u00fade" ) }, 
									1, 4, RadioButtonPanel.ORIENTATION_HORIZONTAL, false );
		JLabel designacaoServicoSaudeLabel = new JLabel( "Designa\u00e7\u00e3o" );
		designacaoServicoSaudeText = new JTextField();
		defaultServicoSaudeButton = new JButton("-");
		defaultServicoSaudeButton.addActionListener( new ActionListener(){
			public void actionPerformed( ActionEvent e )
			{
				designacaoServicoSaudeText.setText( (String) Singleton.getInstance( SingletonConstants.COMPANY_NAME ) );
			}
		} );
		
		JLabel servicoHigieneLabel = new JLabel( "Servi\u00e7o de Higiene e Seguran\u00e7a: Tipo" );
		servicoHigieneTipoPanel = 
			new RadioButtonFixedPanel( new IDObject[]{ new MappableObject( new Integer(1), "Interno" ), 
													new MappableObject( new Integer(2), "Interempresas" ),
													new MappableObject( new Integer(3), "Externo" ), 
													new MappableObject( new Integer(4), "Outro" ) }, 
									1, 4, RadioButtonPanel.ORIENTATION_HORIZONTAL, false );
		JLabel designacaoLabel = new JLabel( "Designa\u00e7\u00e3o" );
		designacaoText = new JTextField();
		defaultServicoHigieneButton = new JButton("-");
		defaultServicoHigieneButton.addActionListener( new ActionListener(){
			public void actionPerformed( ActionEvent e )
			{
				designacaoText.setText(  (String) Singleton.getInstance( SingletonConstants.COMPANY_NAME )  );
			}
		} );
		
		GridBagLayout gridbag = new GridBagLayout();
		setLayout( gridbag );
		GridBagConstraints constraints = new GridBagConstraints();
		constraints.insets = new Insets( 0, 1, 0, 1 );
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.gridwidth = 1;
		constraints.weightx = 0;
		constraints.gridheight = 1;
		constraints.weighty = 0;
		
		gridbag.setConstraints( designacaoSocialLabel, constraints );
		add( designacaoSocialLabel );
		
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( designacaoSocialText, constraints );
		add( designacaoSocialText );
		
		constraints.weightx = 0;
		constraints.gridwidth = 1;
		gridbag.setConstraints( estabelecimentoLabel, constraints );
		add( estabelecimentoLabel );
		
		constraints.weightx = 0.6;
		constraints.gridwidth = 3;
		gridbag.setConstraints( estabelecimentoText, constraints );
		add( estabelecimentoText );
		
		constraints.weightx = 0;
		constraints.gridwidth = 1;
		gridbag.setConstraints( localidadeLabel, constraints );
		add( localidadeLabel );
		
		constraints.weightx = 0.4;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( localidadeText, constraints );
		add( localidadeText );
		
		constraints.weightx = 0;
		constraints.gridwidth = 2;
		gridbag.setConstraints( servicoSaudeLabel, constraints );
		add( servicoSaudeLabel );
		
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( servicoSaudeTipoPanel, constraints );
		add( servicoSaudeTipoPanel );
		
		constraints.weightx = 0;
		constraints.gridwidth = 1;
		gridbag.setConstraints( designacaoServicoSaudeLabel, constraints );
		add( designacaoServicoSaudeLabel );
		
		JPanel designacaoServicoSaudePanel = new JPanel();
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( designacaoServicoSaudePanel, constraints );
		add( designacaoServicoSaudePanel );
		
		constraints.weightx = 0;
		constraints.gridwidth = 3;
		gridbag.setConstraints( servicoHigieneLabel, constraints );
		add( servicoHigieneLabel );
		
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( servicoHigieneTipoPanel, constraints );
		add( servicoHigieneTipoPanel );
		
		constraints.gridwidth = 1;
		constraints.weightx = 0;
		constraints.weighty = 1;
		constraints.gridheight = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( designacaoLabel, constraints );
		add( designacaoLabel );
		
		JPanel designacaoServicoHigienePanel = new JPanel();
		constraints.weightx = 1;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( designacaoServicoHigienePanel, constraints );
		add( designacaoServicoHigienePanel );
		
		gridbag = new GridBagLayout();
		designacaoServicoSaudePanel.setLayout( gridbag );
		constraints.insets = new Insets( 0, 0, 0, 0 );
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.gridwidth = 1;
		constraints.weightx = 1;
		constraints.weighty = 1;
		constraints.gridheight = GridBagConstraints.REMAINDER;
		
		gridbag.setConstraints( designacaoServicoSaudeText, constraints );
		designacaoServicoSaudePanel.add( designacaoServicoSaudeText );
		
		constraints.weightx = 0;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( defaultServicoSaudeButton, constraints );
		designacaoServicoSaudePanel.add( defaultServicoSaudeButton );
		
		
		gridbag = new GridBagLayout();
		designacaoServicoHigienePanel.setLayout( gridbag );
		constraints.insets = new Insets( 0, 0, 0, 0 );
		constraints.fill = GridBagConstraints.HORIZONTAL;
		constraints.gridwidth = 1;
		constraints.weightx = 1;
		constraints.weighty = 1;
		constraints.gridheight = GridBagConstraints.REMAINDER;
		
		gridbag.setConstraints( designacaoText, constraints );
		designacaoServicoHigienePanel.add( designacaoText );
		
		constraints.weightx = 0;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		gridbag.setConstraints( defaultServicoHigieneButton, constraints );
		designacaoServicoHigienePanel.add( defaultServicoHigieneButton );
		
		new CopyPasteHandler( designacaoSocialText );
		new CopyPasteHandler( estabelecimentoText );
		new CopyPasteHandler( localidadeText );
		new CopyPasteHandler( designacaoServicoSaudeText );
		new CopyPasteHandler( designacaoText );
	}
	
	private void setupComponentsHashtable()
	{
		empresaComponents = new ComponentsHashtable();
		empresaComponents.putComponent( EmpresaData.DESIGNACAO_SOCIAL, designacaoSocialText );
		empresaComponents.putComponent( EmpresaData.SERVICO_SAUDE_TIPO, servicoSaudeTipoPanel );
		empresaComponents.putComponent( EmpresaData.SERVICO_SAUDE_DESIGNACAO, designacaoServicoSaudeText );
		empresaComponents.putComponent( EmpresaData.SERVICO_HIGIENE_TIPO, servicoHigieneTipoPanel );
		empresaComponents.putComponent( EmpresaData.SERVICO_HIGIENE_DESIGNACAO, designacaoText );
		
		empresaComponents.putDummy( EmpresaData.MORADA );
		empresaComponents.putDummy( EmpresaData.CODIGO_POSTAL );
		empresaComponents.putDummy( EmpresaData.LOCALIDADE );
		empresaComponents.putDummy( EmpresaData.DISTRITO );
		empresaComponents.putDummy( EmpresaData.CONCELHO );
		empresaComponents.putDummy( EmpresaData.DATA_PROPOSTA );
		empresaComponents.putDummy( EmpresaData.DATA_ACEITACAO );
		empresaComponents.putDummy( EmpresaData.PERFIL_1 );
		empresaComponents.putDummy( EmpresaData.PERFIL_2 );
		empresaComponents.putDummy( EmpresaData.DATA_ENVIO_CONTRATO );
		empresaComponents.putDummy( EmpresaData.DATA_RECEPCAO_CONTRATO );
		empresaComponents.putDummy( EmpresaData.DATA_ENVIO_IDICT );
		empresaComponents.putDummy( EmpresaData.DATA_RELATORIO_ANUAL );
		empresaComponents.putDummy( EmpresaData.CODIGO_1 );
		empresaComponents.putDummy( EmpresaData.CODIGO_2 );
		empresaComponents.putDummy( EmpresaData.CODIGO_3 );
		empresaComponents.putDummy( EmpresaData.CAE );
		empresaComponents.putDummy( EmpresaData.ACTIVIDADE );
		empresaComponents.putDummy( EmpresaData.CONTRIBUINTE );
		empresaComponents.putDummy( EmpresaData.SEGURANCA_SOCIAL );
		empresaComponents.putDummy( EmpresaData.CONTACTO_1 );
		empresaComponents.putDummy( EmpresaData.CONTACTO_2 );
		empresaComponents.putDummy( EmpresaData.SERVICOS );
		empresaComponents.putDummy( EmpresaData.PRECO_HIGIENE );
		empresaComponents.putDummy( EmpresaData.PRECO_MEDICINA );
		empresaComponents.putDummy( EmpresaData.PERIODICIDADE );
		empresaComponents.putDummy( EmpresaData.DESIGNACAO_SOCIAL_PLAIN );
		empresaComponents.putDummy( EmpresaData.DATA_CANCELAMENTO );
		empresaComponents.putDummy( EmpresaData.A_CONSULTAS );
		empresaComponents.putDummy( EmpresaData.A_EXAMES );
		empresaComponents.putDummy( EmpresaData.B_CONSULTAS );
		empresaComponents.putDummy( EmpresaData.B_EXAMES );
		empresaComponents.putDummy( EmpresaData.INICIO_CONTRATO );
		empresaComponents.putDummy( EmpresaData.DURACAO );
		
		estabelecimentoComponents = new ComponentsHashtable();
		estabelecimentoComponents.putComponent( EstabelecimentoData.NOME, estabelecimentoText );
		estabelecimentoComponents.putComponent( EstabelecimentoData.LOCALIDADE, localidadeText );
		estabelecimentoComponents.putDummy( EstabelecimentoData.MORADA );
		estabelecimentoComponents.putDummy( EstabelecimentoData.CODIGO_POSTAL );
		estabelecimentoComponents.putDummy( EstabelecimentoData.CONTACTO );
		estabelecimentoComponents.putDummy( EstabelecimentoData.HISTORICO );
		estabelecimentoComponents.putDummy( EstabelecimentoData.EMPRESA );
		estabelecimentoComponents.putDummy( EstabelecimentoData.NOME_PLAIN );
		
//		components.putComponent( FichaDataProvider.T_EMPRESAS + "." + FichaDataProvider.DESIGNACAO_SOCIAL, designacaoSocialText );
//		components.put( FichaDataProvider.T_EMPRESAS + "." + FichaDataProvider.SERVICO_SAUDE_TIPO, servicoSaudeTipoPanel );
//		components.putComponent( FichaDataProvider.T_EMPRESAS + "." + FichaDataProvider.SERVICO_SAUDE_DESIGNACAO, designacaoServicoSaudeText );
//		components.put( FichaDataProvider.T_EMPRESAS + "." + FichaDataProvider.SERVICO_HIGIENE_TIPO, servicoHigieneTipoPanel );
//		components.putComponent( FichaDataProvider.T_EMPRESAS + "." + FichaDataProvider.SERVICO_HIGIENE_DESIGNACAO, designacaoText );
//		
//		components.putComponent( FichaDataProvider.T_ESTABELECIMENTOS + "." + FichaDataProvider.NOME, estabelecimentoText );
//		components.putComponent( FichaDataProvider.T_ESTABELECIMENTOS + "." + FichaDataProvider.LOCALIDADE, localidadeText );
//		
//		components.putDummy( FichaDataProvider.T_EMPRESAS + "." + FichaDataProvider.INACTIVO );
//		components.putDummy( FichaDataProvider.T_ESTABELECIMENTOS + "." + FichaDataProvider.EMPRESA_ID );
//		components.putDummy( FichaDataProvider.T_ESTABELECIMENTOS + "." + FichaDataProvider.INACTIVO );
	}
	
	public void fill(Object value)
	{
		clear();
		empresa = null;
		estabelecimento = null;
		if( value != null )
		{
			Integer empresaID = (Integer)((Object[])value)[0];
			Integer estabelecimentoID = (Integer)((Object[])value)[1];
			if( empresaID != null )
			{
				try
				{
					empresa = (EmpresaData)JDO.load( EmpresaData.class, empresaID );
					String names[] = (String[])empresaComponents.keySet().toArray( new String[0] );
					ComponentController.fill( names, empresa.getHashData(), empresaComponents );
					
					if( estabelecimentoID != null )
					{
						estabelecimento = (EstabelecimentoData)JDO.load( EstabelecimentoData.class, estabelecimentoID );
						names = (String[])estabelecimentoComponents.keySet().toArray( new String[0] ); //estabelecimento.getFieldNames();
						ComponentController.fill( names, estabelecimento.getHashData(), estabelecimentoComponents );
					}
					
//					DBField fields[] = provider.EMPRESAS.getInsertFields();
//					String empresaFields[] = new String[ fields.length ];
//					Hashtable data = new Hashtable();
//					for( int i = 0; i < empresaFields.length; ++i )
//					{
//						empresaFields[ i ] = fields[ i ].FULL_NAME;
//						Object fieldValue = empresa.getProperty( empresaFields[ i ] );
//						if( fieldValue != null )
//						{
//							data.put( empresaFields[ i ], fieldValue );
//						}
//					}
//					ComponentController.fill( empresaFields, data, components );
//					if( estabelecimentoID != null )
//					{
//						estabelecimento = provider.load( provider.ESTABELECIMENTOS, new DBKey( estabelecimentoID ) );
//						fields = provider.ESTABELECIMENTOS.getInsertFields();
//						String estabelecimentoFields[] = new String[ fields.length ];
//						for( int i = 0; i < estabelecimentoFields.length; ++i )
//						{
//							estabelecimentoFields[ i ] = fields[ i ].FULL_NAME;
//							Object fieldValue = estabelecimento.getProperty( estabelecimentoFields[ i ] );
//							if( fieldValue != null )
//							{
//								data.put( estabelecimentoFields[ i ], fieldValue );
//							}
//						}
//						ComponentController.fill( estabelecimentoFields, data, components );
//					}
				}
				catch( Exception ex )
				{
					DialogException.showExceptionMessage( ex, "Erro a carregar os dados da Empresa", true );
				}
			}
		}
		else
		{
			estabelecimentoText.setText( "Sede" );
		}
	}
	
	public Object save()
	{
		StringBuffer msg = new StringBuffer();
		boolean hasMsg = false;
		try
		{
			if( estabelecimento == null )
			{
//				estabelecimento = provider.createObject( provider.ESTABELECIMENTOS );
				estabelecimento = new EstabelecimentoData();
			}
			if( empresa == null )
			{
//				empresa = provider.createObject( provider.EMPRESAS );
				empresa = new EmpresaData();
			}
//			DBField fields[] = provider.EMPRESAS.getInsertFields();
//			String empresaFields[] = new String[ fields.length ];
//			for( int i = 0; i < empresaFields.length; ++i )
//			{
//				empresaFields[ i ] = fields[ i ].FULL_NAME;
//			}
//			Hashtable hash = new Hashtable();
//			ComponentController.save( empresaFields, hash, components );
//			Enumeration enum = hash.keys();
//			while( enum.hasMoreElements() )
//			{
//				String name = ( String )enum.nextElement();
//				empresa.setProperty( name, hash.get( name ) );
//			}
//			fields = provider.ESTABELECIMENTOS.getInsertFields();
//			String estabelecimentoFields[] = new String[ fields.length ];
//			for( int i = 0; i < estabelecimentoFields.length; ++i )
//			{
//				estabelecimentoFields[ i ] = fields[ i ].FULL_NAME;
//			}
//			hash = new Hashtable();
//			ComponentController.save( estabelecimentoFields, hash, components );
//			enum = hash.keys();
//			while( enum.hasMoreElements() )
//			{
//				String name = ( String )enum.nextElement();
//				estabelecimento.setProperty( name, hash.get( name ) );
//			}
			
			String names[] = (String[])empresaComponents.keySet().toArray( new String[0] );
//			String names[] = new String[]{ EmpresaData.DESIGNACAO_SOCIAL, EmpresaData.SERVICO_SAUDE_TIPO, 
//											EmpresaData.SERVICO_SAUDE_DESIGNACAO, EmpresaData.SERVICO_HIGIENE_TIPO,
//											EmpresaData.SERVICO_HIGIENE_DESIGNACAO };
			Hashtable hash = empresa.getHashData();
			ComponentController.save( names, hash, empresaComponents );
			empresa.setHashData( hash );
			
//			names = estabelecimento.getFieldNames();
			names = (String[])estabelecimentoComponents.keySet().toArray( new String[0] );
			hash = estabelecimento.getHashData();
			ComponentController.save( names, hash, estabelecimentoComponents );
			estabelecimento.setHashData( hash );
			estabelecimento.set( EstabelecimentoData.EMPRESA, empresa );
			
//			estabelecimento.setProperty( provider.R_ESTABELECIMENTO_EMPRESA, empresa );
			
//			if( ((String)empresa.getProperty( provider.DESIGNACAO_SOCIAL )).trim().length() == 0 )
			if( ((String)empresa.get( EmpresaData.DESIGNACAO_SOCIAL )).trim().length() == 0 )
			{
				msg.append( "A empresa tem de ter uma design\u00e7\u00e3o social\n" );
				hasMsg = true;
			}
			else
			{
				empresa.set( EmpresaData.DESIGNACAO_SOCIAL_PLAIN, 
									com.evolute.utils.strings.StringPlainer.convertString( ( String ) 
										empresa.get( EmpresaData.DESIGNACAO_SOCIAL ) ) );
			}
//			if( empresa.getProperty( provider.SERVICO_SAUDE_TIPO ) == null )
			if( empresa.get( EmpresaData.SERVICO_SAUDE_TIPO ) == null )
			{
				msg.append( "A empresa tem de ter um tipo de seri\00e7o de sa\u00fade\n" );
				hasMsg = true;
			}
//			if( empresa.getProperty( provider.SERVICO_HIGIENE_TIPO ) == null )
			if( empresa.get( EmpresaData.SERVICO_HIGIENE_TIPO ) == null )
			{
				msg.append( "A empresa tem de ter um tipo de seri\00e7o de higiene\n" );
				hasMsg = true;
			}
//			if( ((String)estabelecimento.getProperty( provider.NOME )).trim().length() == 0 )
			if( ((String)estabelecimento.get( EstabelecimentoData.NOME )).trim().length() == 0 )
			{
				msg.append( "O estabelecimento tem de ter nome\n" );
				hasMsg = true;
			}
			
		}
		catch( Exception ex )
		{
			ex.printStackTrace();
			return null;
		}
		if( hasMsg )
		{
			throw new ValuesException( msg.toString() );
		}
		return estabelecimento;
		
	}
	
	public void clear()
	{
		String names[] = (String[])empresaComponents.keySet().toArray( new String[0] );
		ComponentController.clear( names, empresaComponents );
		names = (String[])estabelecimentoComponents.keySet().toArray( new String[0] );
		ComponentController.clear( names, estabelecimentoComponents );
		estabelecimentoText.setText( "Sede" );
		empresa = null;
		estabelecimento = null;
	}
	
	public void setEnabled( boolean enable )
	{
		String names[] = (String[])empresaComponents.keySet().toArray( new String[0] );
		ComponentController.setEnabled( names, enable, empresaComponents );
		names = (String[])estabelecimentoComponents.keySet().toArray( new String[0] );
		ComponentController.setEnabled( names, enable, estabelecimentoComponents );
	}
}
