/*
 * MarcacoesHigieneWindow.java
 *
 * Created on January 31, 2006, 11:32 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package siprp.higiene.marcacoes;

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

import com.evolute.utils.*;
import com.evolute.utils.arrays.*;
import com.evolute.utils.data.*;
import com.evolute.utils.jdo.*;
import com.evolute.utils.ui.*;
import com.evolute.utils.ui.panel.*;
import com.evolute.utils.ui.search.*;
import com.evolute.utils.ui.text.*;
import com.evolute.utils.ui.window.*;

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

/**
 *
 * @author fpalma
 */
public class MarcacoesHigieneWindow extends EditorWindow
		implements ItemListener, ActionListener, ListSelectionListener
{
	public final static String TITLE = "Marca\u00e7\u00f5es de Higiene e Seguran\u00e7a";
	
	private final static int iPermissionArray[][] =
		new int[][]{ {}, { NEW_INDEX, EDIT_INDEX, CANCEL_INDEX, SAVE_INDEX, DELETE_INDEX } };
	
	private static final int INDEX_MAIN = 0;
	private static final int INDEX_VISITA = 1;
	
	private static final DateFormat DATE_FORMAT =
			DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "PT", "pt" ) );
	
	protected MarcacoesHigieneUpperPanel upperPanel;
	protected MarcacaoVisitaHSTPanel marcacaoPanel;
	protected TableEditorPanel marcacaoEditorPanel;
	
	protected HigieneDataProvider provider;
	protected JDOProvider JDO;
	protected SIPRPTracker tracker;
	
	private Hashtable tecnicosHash;
	
	protected Integer empresaID;
	protected String empresa;
	protected Integer estabelecimentoID;
	protected EstabelecimentoData estabelecimento;
	
	protected boolean editing = false;
	
	/** Creates a new instance of MarcacoesHigieneWindow */
	public MarcacoesHigieneWindow()	
		throws Exception
	{
		super( iPermissionArray );
		provider = ( HigieneDataProvider ) HigieneDataProvider.getProvider();
		JDO = ( JDOProvider ) Singleton.getInstance( Singleton.DEFAULT_JDO_PROVIDER );
		tecnicosHash = new Hashtable();
		setupComponents();
		setExtendedState(getExtendedState() | MAXIMIZED_BOTH);
	}
	
	private void setupComponents()
		throws Exception
	{
		setTitle( TITLE );
		upperPanel = new MarcacoesHigieneUpperPanel();
		JPanel panel = new JPanel();
		
		GridBagLayout gridbag = new GridBagLayout();
		GridBagConstraints constraints = new GridBagConstraints();
		getContentPane().setLayout( gridbag );
		constraints.insets = new Insets( 2, 2, 2, 2 );
		constraints.fill = GridBagConstraints.BOTH;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.weightx = 1;
		constraints.gridheight = 1;
		
		constraints.weighty = 0.2;
		gridbag.setConstraints( upperPanel, constraints );
		
		constraints.weighty = 0.8;
		gridbag.setConstraints( panel, constraints );
		
		getContentPane().add( upperPanel );
		getContentPane().add( panel );
		
		changeGroupName( INDEX_VISITA, "Visitas" );
		setActionName( INDEX_VISITA, NEW_INDEX, "Nova" );
		setActionTooltip( INDEX_VISITA, NEW_INDEX, "Nova" );
		JPanel toolbar = getToolbarPanel( INDEX_VISITA );
		
		gridbag = new GridBagLayout();
//		GridBagConstraints constraints = new GridBagConstraints();
		panel.setLayout( gridbag );
		constraints.insets = new Insets( 2, 2, 2, 2 );
		constraints.fill = GridBagConstraints.BOTH;
		constraints.gridwidth = GridBagConstraints.REMAINDER;
		constraints.weightx = 1.0;
		constraints.weighty = 0;
		
		gridbag.setConstraints( toolbar, constraints );
		panel.add( toolbar );
		
		constraints.gridheight = 1;
		constraints.weighty = 1.0;
		try
		{
			marcacaoEditorPanel = 
				new TableEditorPanel( new String[]{ "Data", 
					"Estado" },
					new int[]{0,2}, new int[]{0,0},
						0.0, 1.0, new Dimension( 350, 100 ) );
			marcacaoPanel = new MarcacaoVisitaHSTPanel();
			new CopyPasteHandler( marcacaoPanel.getObservacoesText() );
			marcacaoEditorPanel.addComponent( marcacaoPanel, 
					new int[]{0,2}, new int[]{1,2},
					1.0, 1.0 );
			marcacaoEditorPanel.addListSelectionListener( new ListSelectionListener(){
				public void valueChanged(javax.swing.event.ListSelectionEvent listSelectionEvent)
				{
					if( marcacaoEditorPanel.getID() != null )
					{
						reload(INDEX_VISITA);
						select(INDEX_VISITA);
					}
					else
					{
						clear( INDEX_VISITA );
					}
				}
			});
		}catch( Exception ex )
		{
			DialogException.showException( ex );
			return;
		}
		gridbag.setConstraints( marcacaoEditorPanel, constraints );
		panel.add( marcacaoEditorPanel );
		marcacaoPanel.getEmailButton().addActionListener( this );
		
		fillCombo();
		upperPanel.addListSelectionListener( this );
	}
	
	public void fillCombo()
		throws Exception
	{
		marcacaoPanel.getTecnicoList().removeItemListener( this );
		marcacaoPanel.getTecnicoList().removeAllItems();
		tecnicosHash.clear();
		Object tecnicos[][] = provider.getAllTecnicosHST();
		marcacaoPanel.getTecnicoList().addItem( new MappableObject( new Integer( -2 ), " " ) );
		for( int n = 0; n < tecnicos.length; n++ )
		{
			Object tecnico[] = new Object[ 4 ];
			tecnico[ 0 ] = new Integer( ( (Number)tecnicos[n][0] ).intValue() );
			tecnico[ 1 ] = tecnicos[ n ][ 1 ];
			tecnico[ 2 ] = tecnicos[ n ][ 2 ];
			tecnico[ 3 ] = new Integer( n );
			tecnicosHash.put( tecnicos[ n ][ 0 ], tecnico );
			marcacaoPanel.getTecnicoList().addItem( new MappableObject( (Integer) tecnico[ 0 ], tecnico[ 1 ] ) );
		}
		marcacaoPanel.getTecnicoList().setSelectedIndex( 0 );

		marcacaoPanel.getTecnicoList().addItem( new MappableObject( new Integer( -1 ), "Novo/Editar" ) );
		marcacaoPanel.getTecnicoList().addItemListener( this );
	}
	
	public void itemStateChanged(java.awt.event.ItemEvent itemEvent)
	{
		int index = marcacaoPanel.getTecnicoList().getSelectedIndex();
		if( index == marcacaoPanel.getTecnicoList().getItemCount() - 1 )
		{
			try
			{
//				marcacaoPanel.getTecnicoList().removeItemListener( this );
				TecnicoEditor te = new TecnicoEditor( this );
				te.setVisible( true );
//				boolean isNew = me.getIsNew();
				Integer id = te.getID();
				if( id == null )
				{
					marcacaoPanel.getTecnicoList().setSelectedIndex( 0 );
				}
				else
				{
					fillCombo();
					if( id != null )
					{
						Object[] tecnico = (Object[])tecnicosHash.get( id );
						marcacaoPanel.getTecnicoList().setSelectedIndex( ((Integer)tecnico[ 3 ] ).intValue() );
					}
				}
				
			}
			catch( Exception ex )
			{
				DialogException.showExceptionMessage( ex, "Erro na janela de edi\u00e7\u00e3o...", true );
				ex.printStackTrace();
				marcacaoPanel.getTecnicoList().setSelectedIndex( 0 );
				return;
			}
//			finally
//			{
//				marcacaoPanel.getTecnicoList().addItemListener( this );
//			}
		}
		else
		{
			IDObject selected = (IDObject)marcacaoPanel.getTecnicoList().getItemAt( index );
			Integer id = selected.getID();
		}
	}
	
	public boolean save(int index)
	{
		switch( index )
		{
			case INDEX_VISITA:
				MarcacaoEstabelecimentoData visita = ( MarcacaoEstabelecimentoData ) marcacaoPanel.save();
				Date data = ( Date ) visita.get( MarcacaoEstabelecimentoData.DATA );
				if( data == null )
				{
					JOptionPane.showMessageDialog( this, "Tem de preencher uma data para a visita.",
						"Erro", JOptionPane.ERROR_MESSAGE );
					return false;
				}
				visita.set( MarcacaoEstabelecimentoData.ESTABELECIMENTO, estabelecimento );	
				try
				{
					visita.set( MarcacaoEstabelecimentoData.REALIZADA,
								( ( Integer )visita.get( MarcacaoEstabelecimentoData.ESTADO ) ).intValue() ==
									provider.ESTADO_REALIZADO ? "y" : "n" );
					System.out.println( "DATA " + visita.get( MarcacaoEstabelecimentoData.DATA ) );
					Integer tecnico = ( Integer ) visita.get( MarcacaoEstabelecimentoData.TECNICO_HST );
					if( tecnico != null && tecnico.intValue() < 0 )
					{
						visita.set( MarcacaoEstabelecimentoData.TECNICO_HST, null );
					}
					visita.save();
				}
				catch( Exception ex )
				{
					DialogException.showExceptionMessage( ex, "Erro a gravar", true );
					return false;
				}
				
				break;
		}
		reload( INDEX_MAIN );
		editing = false;
		return true;
	}

	public boolean delete(int index)
	{
		int option = JOptionPane.showConfirmDialog( this, "Tem a certeza que quer apagar a marca\u00e7\u00e3o?",
									"Apagar", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE );
		if( option == 0 )
		{
			switch( index )
			{
				case INDEX_VISITA:
					MarcacaoEstabelecimentoData visita = ( MarcacaoEstabelecimentoData ) marcacaoPanel.save();
					try
					{
						visita.delete();
					}
					catch( Exception ex )
					{
						DialogException.showExceptionMessage( ex, "Erro a apagar.", true );
						return false;
					}
					break;
			}
			reload( INDEX_MAIN );
			return true;
		}
		return false;
	}

	public void clear(int index)
	{
		switch( index )
		{
			case INDEX_MAIN:
				empresaID = null;
				empresa = null;
				estabelecimentoID = null;
				estabelecimento = null;
				upperPanel.clear();
				marcacaoEditorPanel.clear();
				break;
				
			case INDEX_VISITA:
				marcacaoPanel.clear();
				marcacaoPanel.getEmailButton().setText( "Enviar email" );
				break;
		}
	}

	public void enableComponents(int index, boolean enable)
	{
		switch( index )
		{
			case INDEX_MAIN:
				
				break;
			
			case INDEX_VISITA:
				marcacaoPanel.setEnabled( enable );
				marcacaoPanel.getEmailButton().setEnabled( enable );
				upperPanel.setEnabled( !enable );
				editing = enable;
				break;
		}
		if( tracker != null )
		{
			tracker.getAvisosPanel().setEnabled( !editing,
													AvisoConstants.TIPO_ESTABELECIMENTO );
		}
	}
	
	protected void enableSelect( int index, boolean select )
	{
		switch( index )
		{
			case INDEX_VISITA:
				marcacaoEditorPanel.setEnabled( select );
				break;
		}
	}
	
	public void reload( int index )
	{
		switch( index )
		{
			case INDEX_MAIN:
				try
				{
					empresa = provider.getEmpresa( empresaID );
					estabelecimento = ( EstabelecimentoData ) JDO.load( EstabelecimentoData.class, estabelecimentoID );
//					upperPanel.getEmpresaText().setText( empresa );
//					upperPanel.getEstabelecimentoText().setText( estabelecimento );
//					upperPanel.getTrabalhadorText().setText( ( String ) trabalhador.get( TrabalhadorData.NOME ) );
					Object visitas[][] = provider.getVisitasEstabelecimento( estabelecimentoID );
					if( visitas.length > 0 )
					{
						marcacaoEditorPanel.setData( new Object2DArray( visitas ) );
					}
					else
					{
						marcacaoEditorPanel.clear();
					}
				}
				catch( Exception ex )
				{
					DialogException.showExceptionMessage( ex, "Erro a carregar os dados.", true );
				}
				break;
				
			case INDEX_VISITA:
				Integer visitaID = marcacaoEditorPanel.getID();
				if( visitaID == null )
				{
					return;
				}
				try
				{
					MarcacaoEstabelecimentoData visita = 
							( MarcacaoEstabelecimentoData ) JDO.load( MarcacaoEstabelecimentoData.class, visitaID );			
					marcacaoPanel.fill( visita );
					Date dataEmailVisita = ( Date ) visita.get( MarcacaoEstabelecimentoData.DATA_EMAIL );
					if( dataEmailVisita != null )
					{
						marcacaoPanel.getEmailButton().setText( "Enviar email (" + DATE_FORMAT.format( dataEmailVisita ) + ")" );
					}
					else
					{
						marcacaoPanel.getEmailButton().setText( "Enviar email" );
					}
				}
				catch( Exception ex )
				{
					DialogException.showExceptionMessage( ex, "Erro a carregar os dados da visita.", true );
				}
				break;
		}
	}
	
	public void actionPerformed( ActionEvent e )
	{
		Object source = e.getSource();
		if( source.equals( marcacaoPanel.getEmailButton() ) )
		{
			enviarEmailVisita();
		}
	}
		
	protected void enviarEmailVisita()
	{
		MarcacaoEstabelecimentoData visita = ( MarcacaoEstabelecimentoData ) marcacaoPanel.save();
		
		String subject = ( String ) Singleton.getInstance( SingletonConstants.SUBJECT_VISITA );
		String texto = ( String ) Singleton.getInstance( SingletonConstants.LETTER_VISITA );
		
		Date today = new Date();
		marcacaoPanel.getEmailButton().setText( "Enviar email (" + DATE_FORMAT.format( today ) + ")" );
		
		try
		{
			enviarEmail( subject, texto, ( Date )visita.get( MarcacaoEstabelecimentoData.DATA ) );
			visita.set( Marcacao.DATA_EMAIL, today );
		}
		catch( Exception ex )
		{
			DialogException.showExceptionMessage( ex, "Erro a enviar mail", true );
		}
	}
	
	protected void enviarEmail( String subject, String texto, Date data )
		throws Exception
	{
		String sede = ( String )estabelecimento.get( EstabelecimentoData.NOME );
		String dataStr = DATE_FORMAT.format( data );
		subject = subject.replaceAll( CompanyDataLoader.NOME, sede );
		String morada = ( String )estabelecimento.get( EstabelecimentoData.MORADA );
		
		texto = texto.replaceAll( CompanyDataLoader.DATA, dataStr );
		texto = texto.replaceAll( CompanyDataLoader.NOME, sede );
		texto = texto.replaceAll( CompanyDataLoader.MORADA, morada );
		
		ContactoData contacto = ( ContactoData )estabelecimento.get( EstabelecimentoData.CONTACTO );
		String mail = "";
		if( contacto != null )
		{
			mail = ( String )contacto.get( ContactoData.EMAIL );
		}
		
		if( System.getProperty( "os.name" ).startsWith( "Windows" ) )
		{
			mail = mail.replaceAll( " ", "%20" );
			subject = subject.replaceAll( " ", "%20" );
			texto = texto.replaceAll( " ", "%20" );
			Process proc = Runtime.getRuntime().exec( "cmd.exe /c start mailto:\"" + mail 
				+ "?subject=" + subject + "&body="

				+ texto
				 );
		}
		else
		{
			mail = mail.replaceAll( " ", "%20" );
			subject = subject.replaceAll( " ", "%20" );
			texto = texto.replaceAll( " ", "%20" );

			Process proc = Runtime.getRuntime().exec( new String[]{ "/usr/bin/open", "/Applications/Mail.app", "mailto:" + mail 
				+ "?subject=" + subject + "&body="
				+ texto } );
		}
	}
	
	public void valueChanged( ListSelectionEvent e )
	{
		Object source = e.getSource();
		if( source.equals( upperPanel ) )
		{
			Integer ids[] = ( Integer [] ) upperPanel.save();
			empresaID = ids[ 0 ];
			estabelecimentoID = ids[ 1 ];
			if( ids[ 1 ] == null )
			{
				clear( INDEX_MAIN );
				unselect( INDEX_MAIN ); 
			}
			else
			{
				reload( INDEX_MAIN );
				select( INDEX_MAIN );
			}
		}
	}
	
	public void setEmpresaAndEstabelecimento( Integer empresaID, Integer estabelecimentoID )
	{
		if( editing )
		{
			JOptionPane.showMessageDialog( this, "Esta janela est\u00e1 em edi\u00e7\u00e3o.", "Erro...",
					JOptionPane.ERROR_MESSAGE );
		}
		else
		{
			upperPanel.fill( new Integer[]{ empresaID, estabelecimentoID } );
		}
	}
	
	public void setTracker( SIPRPTracker tracker )
	{
		this.tracker = tracker;
	}
}
