package siprp.medicina.exames.ui;

import static com.evolute.utils.strings.UnicodeLatin1Map.atilde;
import static com.evolute.utils.strings.UnicodeLatin1Map.ccedil;
import info.clearthought.layout.TableLayout;
import info.clearthought.layout.TableLayoutConstraints;

import java.awt.Dimension;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.ListSelectionModel;

import leaf.data.OrderedMap;
import leaf.ui.LeafButton;
import leaf.ui.LeafInputField;
import leaf.ui.LeafTableModel;
import leaf.ui.LeafWindow;
import leaf.ui.LeafLogic.LeafUIActionBinding;
import siprp.database.cayenne.objects.Empresas;
import siprp.database.cayenne.objects.Estabelecimentos;
import siprp.database.cayenne.objects.Prestadores;
import siprp.database.cayenne.objects.Trabalhadores;
import siprp.database.cayenne.objects.TrabalhadoresEcd;
import siprp.database.cayenne.objects.TrabalhadoresEcds;
import siprp.database.cayenne.objects.TrabalhadoresEcdsDatas;
import siprp.medicina.exames.logic.RecepcaoExamesLogic;

import com.evolute.utils.tables.BaseTable;

public class RecepcaoExamesWindow extends LeafWindow
{
	private static final long serialVersionUID = 1L;

	public static final String TITLE = "Recep" + ccedil + atilde + "o de ECDs";
	
	private static final String TRABALHADOR = "Trabalhador";
	private static final String EMPRESA = "Empresa";

	public final JLabel labelAnalisador = new JLabel( "Analisador" );

	@ActionActivation(onSelect = RecepcaoExamesLogic.ACTION_SELECT_EXAME, onChange = "")
	public BaseTable examesTable;
	public LeafTableModel examesModel;
	public JScrollPane examesScroll;

	@ActionActivation(onSelect = "", onChange = RecepcaoExamesLogic.ACTION_SELECT_ANALISADOR)
	public final LeafInputField<OrderedMap<Prestadores>> fieldAnalisador = new LeafInputField<OrderedMap<Prestadores>>();

	public final JLabel labelData = new JLabel( "Data de recep" + ccedil + atilde + "o" );
	public final LeafInputField<Date> fieldData = new LeafInputField<Date>();
	
	public final JLabel labelOrder = new JLabel("Ordenar por: ");
	@ActionActivation(onSelect="", onChange=RecepcaoExamesLogic.ACTION_SORT)
	public final LeafInputField<OrderedMap<String>> fieldOrder = new LeafInputField<OrderedMap<String>>();

	@ActionActivation(onSelect=RecepcaoExamesLogic.ACTION_RECEBER_EXAMES, onChange="")
	public final LeafButton buttonReceber = new LeafButton( "Receber" );

	public final JPanel pane = new JPanel();

	public RecepcaoExamesWindow()
	{
		super( new RecepcaoExamesLogic() );
		setTitle( TITLE );
		setupLayout();
		setupComponents();
		placeComponents();
		completeSetup();
	}

	private void setupLayout()
	{
		double[] cols = new double[] {
				TableLayout.PREFERRED, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.PREFERRED
		};
		double[] rows = new double[] {
				TableLayout.PREFERRED, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.PREFERRED
		};
		TableLayout layout = new TableLayout( cols, rows );
		layout.setHGap( 5 );
		layout.setVGap( 5 );
		pane.setLayout( layout );
	}

	private void setupComponents()
	{
		setContentPane( pane );
		examesModel = new LeafTableModel( new String[] {
		                                      			"Empresa", "Estabelecimento", "Trabalhador", "Exame (tipo)", "Exame"
		                                      		} );
		examesTable = new BaseTable( examesModel );
		examesTable.setSelectionMode( ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
//		examesTable.setNonResizableNorReordable();
		examesTable.getTableHeader().setResizingAllowed( true );
		examesTable.getTableHeader().setReorderingAllowed( false );
		examesScroll = new JScrollPane( examesTable, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_NEVER );
		
		OrderedMap<String> orderOptions = new OrderedMap<String>();
		orderOptions.putLast( EMPRESA, EMPRESA );
		orderOptions.putLast( TRABALHADOR, TRABALHADOR );
		fieldOrder.setObject( orderOptions, EMPRESA );
		fieldOrder.setEditable( true );
	}
	
	private JPanel createMargin(boolean horizontal, int marginSize)
	{
		JPanel result = new JPanel();
		Dimension dim = new Dimension(horizontal ? 0 : marginSize, horizontal ? marginSize: 0 );
		result.setPreferredSize( dim );
		result.setSize( dim );
		return result;
	}

	private void placeComponents()
	{
		pane.add( createMargin(true, 20), new TableLayoutConstraints(0,0,0,5));
		pane.add( createMargin(true, 20), new TableLayoutConstraints(7,0,7,5));
		pane.add( createMargin(false, 20), new TableLayoutConstraints(0,0,7,0));
		pane.add( createMargin(false, 20), new TableLayoutConstraints(0,5,7,5));
		pane.add( labelAnalisador, new TableLayoutConstraints( 1, 1, 2, 1 ) );
		pane.add( fieldAnalisador, new TableLayoutConstraints( 1, 2, 4, 2 ) );
		pane.add( labelData, new TableLayoutConstraints( 1, 3 ) );
		pane.add( fieldData, new TableLayoutConstraints( 1, 4, 2, 4 ) );
		pane.add( buttonReceber, new TableLayoutConstraints( 4, 4 ) );
		pane.add( examesScroll, new TableLayoutConstraints( 1, 5, 4, 5 ) );
		pane.add( labelOrder, new TableLayoutConstraints( 1, 6 ) );
		pane.add( fieldOrder, new TableLayoutConstraints( 2, 6, 3, 6 ) );
	}

	@LeafUIActionBinding(action = RecepcaoExamesLogic.ACTION_FILL_EXAMES)
	public void fillExames(Collection<TrabalhadoresEcd> exames)
	{
		examesTable.clearSelection();
		examesModel.clearAll();
		if(exames != null)
		{
			OrderedMap<TrabalhadoresEcd> orderedMap = new OrderedMap<TrabalhadoresEcd>();
			for( TrabalhadoresEcd current : exames )
			{
				TrabalhadoresEcdsDatas exameMarcacao = current.getToTrabalhadoresEcdsDatas();
				Empresas empresa = null;
				Estabelecimentos estabelecimento = null;
				Trabalhadores trabalhador = null;
				TrabalhadoresEcds exame = null;
				if( exameMarcacao != null )
				{
					exame = exameMarcacao.getToTrabalhadoresEcds();
					if( exame != null)
					{
						trabalhador = exame.getToTrabalhadores();
						if( trabalhador != null )
						{
							estabelecimento = trabalhador.getToEstabelecimentos();
							if( estabelecimento != null )
							{
								empresa = estabelecimento.getToEmpresas();
							}
						}
					}
				}
				orderedMap.putLast( current, empresa, estabelecimento, trabalhador, current.getToPrtTiposElementosProtocolo().getToPrtGruposProtocolo(), current );
			}
			orderedMap.order( new int[]{ 0, 1, 2, 3, 4 } );
			examesModel.setValues( orderedMap );
		}
	}
	
	@LeafUIActionBinding(action=RecepcaoExamesLogic.ACTION_SORT)
	public void sort()
	{
		Object selected = fieldOrder.getSelectedObject();
		if( selected != null )
		{
			if(selected.toString().equals( TRABALHADOR ))
			{
				examesModel.order( 2, 3, 4 );	
			}else
			{
				examesModel.order( 0, 1, 2, 3, 4 );
			}
		}
	}
	
	@LeafUIActionBinding(action = RecepcaoExamesLogic.ACTION_SELECT_ANALISADOR)
	public Prestadores selectAnalisador()
	{
		return (Prestadores)fieldAnalisador.getSelectedObject();
	}
	
	@LeafUIActionBinding(action = RecepcaoExamesLogic.ACTION_RECEBER_EXAMES)
	public List<TrabalhadoresEcd> receberExames()
	{
		List<TrabalhadoresEcd> result = new ArrayList<TrabalhadoresEcd>();
		int [] selectedRows = examesTable.getSelectedRows();
		if( selectedRows != null )
		{
			for( int i = 0; i < selectedRows.length; ++i)
			{
				Object ecd = examesModel.getKey( selectedRows[i] );
				if(ecd != null)
				{
					if( ecd instanceof TrabalhadoresEcd)
					{
						((TrabalhadoresEcd) ecd ).setDataRecepcao( fieldData.getObject() );
						result.add( (TrabalhadoresEcd) ecd );
					}
				}
			}
		}
		runActionLater( RecepcaoExamesLogic.ACTION_SELECT_ANALISADOR );
		return result;
	}
	
	@LeafUIActionBinding(action = RecepcaoExamesLogic.ACTION_STARTUP)
	public void startup()
	{
		List<Prestadores> prestadores = Prestadores.getAllPrestadores();
		Prestadores prestador = (prestadores == null || prestadores.size() == 0) ? null : prestadores.get( 0 );
		OrderedMap<Prestadores> allPrestadores = new OrderedMap<Prestadores>( prestadores );
		fieldAnalisador.setObject( allPrestadores, prestador );
		fieldAnalisador.setEditable( true );

		fieldData.setObject( new Date() );
		fieldData.setEditable( true );
		
		runActionLater( RecepcaoExamesLogic.ACTION_SELECT_ANALISADOR );
	}

}
