package siprp.medicina.locais_analise;

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

import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.text.DateFormat;
import java.util.Date;
import java.util.Locale;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingUtilities;
import javax.swing.WindowConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import siprp.medicina.locais_realizacao.LocaisRealizacaoConstants;

import com.evolute.utils.data.IDObject;
import com.evolute.utils.dataui.ControllableComponent;
import com.evolute.utils.tracker.TrackableWindow;
import com.evolute.utils.ui.DialogException;
import com.evolute.utils.ui.calendar.JCalendarPanel;
import com.evolute.utils.ui.panel.CheckBoxPanel;

public class EnviarAnalisesWindow extends JFrame
	implements TrackableWindow, ActionListener, ChangeListener, ControllableComponent
{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	public static final String TITLE = "Enviar ECDs SIPRP para An\u00e1lise";
	
	protected JCalendarPanel dataPanel;
	protected JComboBox prestadorCombo;
	protected JPanel ecdsOuterPanel;
	protected CheckBoxPanel ecdsPanel;
	protected JButton enviarButton;
	
	protected final EnviarAnalisesWindowLogic logic;

	public EnviarAnalisesWindow()
		throws Exception
	{
		logic = new EnviarAnalisesWindowLogic( this );
		setupComponents();
	}
	
	private void setupComponents()
	{
		setTitle( TITLE );
		setSize( 500, 400 );
		
		JLabel dataLabel = new JLabel( "Data" );
		dataPanel = new JCalendarPanel( this );
		dataPanel.addChangeListener( this );
		JLabel prestadorLabel = new JLabel( "Analisador" );
		prestadorCombo = new JComboBox();
		ecdsOuterPanel = new JPanel();
		ecdsOuterPanel.setLayout( new GridLayout( 1, 1 ) );
		enviarButton = new JButton( "Gravar" );
		enviarButton.addActionListener( this );
		
		TableLayout layout = 
			new TableLayout( 
				new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.PREFERRED,
								TableLayoutConstraints.MINIMUM, TableLayoutConstraints.PREFERRED },
				new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL,
								TableLayoutConstraints.MINIMUM } );
		layout.setHGap( 2 );
		layout.setVGap( 2 );
		getContentPane().setLayout( layout );
		
		getContentPane().add( dataLabel, new TableLayoutConstraints( 0, 0 ) );
		getContentPane().add( dataPanel, new TableLayoutConstraints( 1, 0 ) );
		getContentPane().add( prestadorLabel, new TableLayoutConstraints( 2, 0 ) );
		getContentPane().add( prestadorCombo, new TableLayoutConstraints( 3, 0 ) );
		getContentPane().add( ecdsOuterPanel, new TableLayoutConstraints( 0, 1, 3, 1 ) );
		getContentPane().add( enviarButton, new TableLayoutConstraints( 1, 2, 2, 2 ) );
		
		
		setDefaultCloseOperation( WindowConstants.DO_NOTHING_ON_CLOSE );
		addWindowListener( new WindowAdapter(){
			public void windowClosing( WindowEvent e )
			{
				close();
			}
			
			public void windowOpened( WindowEvent e )
			{
//				setExtendedState( getExtendedState() | MAXIMIZED_BOTH );
			}
			
		} );
		dataPanel.setDate( new Date() );
		try
		{
			logic.dateChanged( dataPanel.getDate() );
		}
		catch( Exception ex )
		{
			if( dataPanel.getDate() != null )
			{
				DialogException.showExceptionMessage( ex, "Erro a carregar dados de " + DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "pt", "PT" ) ).format( dataPanel.getDate() ), true );
			}
			else
			{
				DialogException.showExceptionMessage( ex, "Erro a carregar dados de null", true );
			}
		}
	}
	
	public void refresh()
	{
	}

	public void open()
	{
		setVisible( true );
	}
	
	public void close()
	{
		SwingUtilities.invokeLater( new Runnable() {
			public void run()
			{
				setVisible( false );
				dispose();
			}
		} );
	}

	public boolean closeIfPossible()
	{
		close();
		return true;
	}
	
	protected void setPrestadores( IDObject prestadores[] )
	{
		prestadorCombo.removeAllItems();
		for( IDObject prestador : prestadores )
		{
			prestadorCombo.addItem( prestador );
		}
//		revalidate();
	}
	
	public void setEcds( IDObject ecds[] )
	{
		ecdsPanel = new CheckBoxPanel( ecds );
		ecdsOuterPanel.removeAll();
		ecdsOuterPanel.add( ecdsPanel );
		revalidate();
	}

	@Override
	public void actionPerformed( ActionEvent e )
	{
		Object source = e.getSource();
		if( source.equals( enviarButton ) )
		{
			try
			{
				logic.save();
			}
			catch( Exception ex )
			{
				DialogException.showExceptionMessage( ex, "Erro a gravar", true );
			}
		}
	}

	@Override
	public void stateChanged( ChangeEvent e )
	{
		Object source = e.getSource();
		if( source.equals( dataPanel ) )
		{
			Date data = dataPanel.getDate();
			try
			{
				logic.dateChanged( data );
			}
			catch( Exception ex )
			{
				if( data != null )
				{
					DialogException.showExceptionMessage( ex, "Erro a carregar dados de " + DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "pt", "PT" ) ).format( data ), true );
				}
				else
				{
					DialogException.showExceptionMessage( ex, "Erro a carregar dados de null", true );
				}
			}
		}
	}

	@Override
	public void clear()
	{
		if( prestadorCombo.getItemCount() > 0 )
		{
			prestadorCombo.setSelectedIndex( 0 );
			if( ecdsPanel != null )
			{
				ecdsPanel.clear();
			}
		}
	}

	@Override
	public void fill( Object value )
	{
		clear();
		if( value != null )
		{
			Date data = ( Date ) ( ( Object[] ) value )[ 0 ];
			Integer prestadorId = ( Integer ) ( ( Object[] ) value )[ 1 ];
			Integer ecdsEscolhidos[] = ( Integer[] ) ( ( Object[] ) value )[ 2 ];
			if( prestadorId == null )
			{
				prestadorCombo.setSelectedIndex( 0 );
			}
			else
			{
				for( int n = 0; n < prestadorCombo.getItemCount(); n++ )
				{
					IDObject prestador = ( IDObject ) prestadorCombo.getItemAt( n );
					if( prestadorId.equals( prestador.getID() ) )
					{
						prestadorCombo.setSelectedIndex( n );
					}
				}
			}
			ecdsPanel.fill( ecdsEscolhidos );
		}
	}

	@Override
	public Object save()
	{
		return new Object[]{ 
				dataPanel.getDate(), 
				( ( IDObject )prestadorCombo.getSelectedItem() ).getID(),
				ecdsPanel != null ? ecdsPanel.save() : null };
	}
	
	private void revalidate()
	{
		( ( JPanel ) getContentPane() ).revalidate();
	}
}
