package siprp.medicina.processo.detalhes;

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

import java.awt.GridLayout;
import java.text.DateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Vector;

import javax.swing.BorderFactory;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextField;

import siprp.medicina.MedicinaConstants;
import siprp.medicina.MedicinaDataProvider;
import siprp.medicina.processo.ProcessoDataProvider;
import siprp.medicina.processo.data.TrabalhadoresConsultasData;
import siprp.medicina.processo.data.TrabalhadoresProcessoData;

import com.evolute.utils.dataui.ControllableComponent;
import com.evolute.utils.tables.BaseTable;
import com.evolute.utils.tables.ColumnizedObjectArray;
import com.evolute.utils.tables.VectorTableModel;
import com.evolute.utils.ui.DialogException;

public class ProcessoInfoPanel 
	extends JPanel
	implements ControllableComponent 
{
	protected static final DateFormat D_F = DateFormat.getDateInstance( DateFormat.SHORT, new Locale( "pt", "PT" ) );
	
	protected JFrame owner;
	protected JTextField descricaoText;
	protected JTextField estadoECDsText;
	protected BaseTable ecdsTable;
	protected VectorTableModel ecdsModel;
	protected JTextField estadoConsultasText;
	protected BaseTable consultasTable;
	protected VectorTableModel consultasModel;
	protected JTextField estadoFichaAptidaoText;
	protected BaseTable fichaAptidaoTable;
	protected VectorTableModel fichaAptidaoModel;
	
	protected  ProcessoDataProvider processoProvider; 
	
	public ProcessoInfoPanel( JFrame owner )
		throws Exception
	{
		this.owner = owner;
		processoProvider = ProcessoDataProvider.getProvider();
		setupComponents();
	}
	
	private void setupComponents()
	{
		descricaoText = new JTextField();
		descricaoText.setEditable( false );
		JLabel estadoECDsLabel = new JLabel( "Estado" );
		estadoECDsText = new JTextField(); 
		estadoECDsText.setEditable( false );
		ecdsModel = new VectorTableModel( new String[]{ "Situa\u00e7\u00e3o", "#", "\u00DAltima Data" } );
		ecdsTable = new BaseTable( ecdsModel );
		JScrollPane ecdsScroll = 
			new JScrollPane( ecdsTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
										JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
		JLabel estadoConsultasLabel = new JLabel( "Estado" );
		estadoConsultasText = new JTextField();
		estadoConsultasText.setEditable( false );
		consultasModel = new VectorTableModel( new String[]{ "Situa\u00e7\u00e3o", "#", "\u00DAltima Data" } );
		consultasTable = new BaseTable( consultasModel );
		JScrollPane consultasScroll = 
			new JScrollPane( consultasTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
										JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
		JLabel estadoFichaAptidaoLabel = new JLabel( "Estado" );
		estadoFichaAptidaoText = new JTextField();
		estadoFichaAptidaoText.setEditable( false );
		fichaAptidaoModel = new VectorTableModel( new String[]{ "Situa\u00e7\u00e3o", "Resultado", "\u00DAltima Data" } );
		fichaAptidaoTable = new BaseTable( fichaAptidaoModel );
		JScrollPane fichaAptidaoScroll = 
			new JScrollPane( fichaAptidaoTable, JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED,
										JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED );
		
		JPanel ecdsPanel = new JPanel();
		ecdsPanel.setBorder( 
				BorderFactory.createTitledBorder( 
						BorderFactory.createEtchedBorder(),
						"ECDs") );
		double ecdsRows[] = new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL };
		double ecdsCols[] = new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL };
		TableLayout ecdsLayout = new TableLayout( ecdsCols, ecdsRows );
		ecdsPanel.setLayout( ecdsLayout );
		ecdsPanel.add( estadoECDsLabel, new TableLayoutConstraints( 0, 0 ) );
		ecdsPanel.add( estadoECDsText, new TableLayoutConstraints( 1, 0 ) );
		ecdsPanel.add( ecdsScroll, new TableLayoutConstraints( 0, 1, 1, 1 ) );
		
		JPanel consultasPanel = new JPanel();
		consultasPanel.setBorder( 
				BorderFactory.createTitledBorder( 
						BorderFactory.createEtchedBorder(),
						"Consultas") );
		double consultasRows[] = new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL };
		double consultasCols[] = new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL };
		TableLayout consultasLayout = new TableLayout( consultasCols, consultasRows );
		consultasPanel.setLayout( consultasLayout );
		consultasPanel.add( estadoConsultasLabel, new TableLayoutConstraints( 0, 0 ) );
		consultasPanel.add( estadoConsultasText, new TableLayoutConstraints( 1, 0 ) );
		consultasPanel.add( consultasScroll, new TableLayoutConstraints( 0, 1, 1, 1 ) );
		
		JPanel fichaAptidaoPanel = new JPanel();
		fichaAptidaoPanel.setBorder( 
				BorderFactory.createTitledBorder( 
						BorderFactory.createEtchedBorder(),
						"Ficha de Aptid\u00e3o") );
		double fichaAptidaoRows[] = new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL };
		double fichaAptidaoCols[] = new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL };
		TableLayout fichaAptidaoLayout = new TableLayout( fichaAptidaoCols, fichaAptidaoRows );
		fichaAptidaoPanel.setLayout( fichaAptidaoLayout );
		fichaAptidaoPanel.add( estadoFichaAptidaoLabel, new TableLayoutConstraints( 0, 0 ) );
		fichaAptidaoPanel.add( estadoFichaAptidaoText, new TableLayoutConstraints( 1, 0 ) );
		fichaAptidaoPanel.add( fichaAptidaoScroll, new TableLayoutConstraints( 0, 1, 1, 1 ) );
		
		double rows[] = new double[]{ TableLayoutConstraints.MINIMUM, TableLayoutConstraints.FILL, 
										TableLayoutConstraints.FILL, TableLayoutConstraints.FILL };  
		double cols[] = new double[]{ TableLayoutConstraints.FILL };
		TableLayout layout = new TableLayout( cols, rows );
		layout.setHGap( 5 );
		layout.setVGap( 5 );
		setLayout( layout );
		add( descricaoText, new TableLayoutConstraints( 0, 0 ) );
		add( ecdsPanel, new TableLayoutConstraints( 0, 1 ) );
		add( consultasPanel, new TableLayoutConstraints( 0, 2 ) );
		add( fichaAptidaoPanel, new TableLayoutConstraints( 0, 3 ) );
	}
	
	@Override
	public void setEnabled( boolean enabled )
	{
		// TODO Auto-generated method stub
		super.setEnabled( enabled );
	}

	@Override
	public void clear()
	{
		descricaoText.setText( "" );
		ecdsModel.clearAll();
		consultasModel.clearAll();
		fichaAptidaoModel.clearAll();
	}

	@Override
	public Object save()
	{
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void fill( Object value )
	{
		clear();
		Integer id = ( Integer ) value;
		if( id != null )
		{
			try
			{
				TrabalhadoresProcessoData processo = processoProvider.getProcessoByID( id );
				if( processo == null )
				{
					throw new Exception( "Processo n\u00e3o existente: " + id );
				}
				Date dataInicio = ( Date ) processo.get( TrabalhadoresProcessoData.DATA_INICIO );
				Date dataFim = ( Date ) processo.get( TrabalhadoresProcessoData.DATA_FIM );
				String codigoEstado = ( String ) processo.get( TrabalhadoresProcessoData.ESTADO );
				String estado = processoProvider.getDescricaoEstadoProcessoByCodigo( codigoEstado );
				String desc = D_F.format( dataInicio );
				Integer motivo = ( Integer ) processo.get( TrabalhadoresProcessoData.MOTIVO );
				desc += ": " + MedicinaDataProvider.MOTIVOS_BY_ID.get( motivo ) + " : " + estado;
				descricaoText.setText( desc );
				
				Integer consultaIds[] = processoProvider.getConsultaIDsForProcesso( id );
				Arrays.sort( consultaIds );
				HashMap<Integer,Integer> numeroConsultasPorEstado = new HashMap<Integer,Integer>();
				HashMap<Integer,Date> dataConsultaPorEstado = new HashMap<Integer,Date>();
				for( int n = 0; n < consultaIds.length; n++ )
				{
					TrabalhadoresConsultasData consulta = processoProvider.getConsultaByID( consultaIds[ n ] );
					Date dataConsulta = ( Date ) consulta.get( TrabalhadoresConsultasData.DATA );
					Integer estadoConsulta = ( Integer ) consulta.get( TrabalhadoresConsultasData.ESTADO );
					if( estadoConsulta != null )
					{
						Integer oldCount = numeroConsultasPorEstado.get( estadoConsulta );
						if( oldCount == null )
						{
							oldCount = new Integer( 0 );
						}
						numeroConsultasPorEstado.put( estadoConsulta, new Integer( oldCount.intValue() + 1 ) );
					}
					dataConsultaPorEstado.put( estadoConsulta, dataConsulta );
				}
				Vector consultasValues = consultasModel.getValues();
				Integer estadosConsultaUsados[] = numeroConsultasPorEstado.keySet().toArray( new Integer[ numeroConsultasPorEstado.size() ] );
				Arrays.sort( estadosConsultaUsados );
				for( int n = 0; n < estadosConsultaUsados.length; n++ )
				{
					String estadoStr = MedicinaConstants.ESTADOS_CONSULTA_STR[ estadosConsultaUsados[ n ].intValue() ];
					Integer numero = numeroConsultasPorEstado.get( estadosConsultaUsados[ n ] );
					Date dataUltimaConsulta = dataConsultaPorEstado.get( estadosConsultaUsados );
					Object linha[] = new Object[]{ estadoStr, numero, dataUltimaConsulta };
					consultasValues.add( new ColumnizedObjectArray( linha, false ) );
				}
				consultasModel.setValues( consultasValues );
			}
			catch( Exception ex )
			{
				DialogException.showExceptionMessage( ex, "Erro a carregar dados do processo", true );
				return;
			}
		}
		
	}
}
