package siprp.higiene.relatorio;

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

import java.awt.Component;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Date;
import java.util.EventObject;

import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JTabbedPane;
import javax.swing.JTextField;
import javax.swing.event.CaretEvent;
import javax.swing.event.CaretListener;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

import leaf.ui.LeafError;
import leaf.ui.LeafIconButton;
import siprp.database.cayenne.objects.HsRelatorio;
import siprp.database.cayenne.objects.MarcacoesEstabelecimento;
import siprp.database.cayenne.objects.MarcacoesTecnicosHst;
import siprp.higiene.gestao.equipamentos.AdicionarEquipamentosPanel;

import com.evolute.utils.ui.calendar.JCalendarPanel;

public class PanelRelatorio extends JPanel implements CaretListener, ChangeListener, ActionListener
{

	private static final long serialVersionUID = 1L;

	private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/riscos/save.png";
	private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/riscos/revert.png";
	private static final String ICON_NAME_SUBMIT = "siprp/higiene/relatorio/submit.png";

	private final JCalendarPanel dataRelatorio = new JCalendarPanel( null );

	private final JRadioButton radioInicial = new JRadioButton( "Inicial" );
	private final JRadioButton radioPeriodica = new JRadioButton( "Peri" + oacute + "dica" );

	private final JTextField fieldTecnico = new JTextField();

	private final JPanel panelAcompanhantes = new JPanel();

	private final JTextField fieldNome1 = new JTextField();
	private final JTextField fieldNome2 = new JTextField();
//	private final JTextField fieldNome3 = new JTextField();

	private final JTextField fieldFuncao1 = new JTextField();
	private final JTextField fieldFuncao2 = new JTextField();
//	private final JTextField fieldFuncao3 = new JTextField();

	private final LeafIconButton buttonSave = LeafIconButton.createButton( ICON_NAME_SAVE );
	private final LeafIconButton buttonRevert = LeafIconButton.createButton( ICON_NAME_REVERT );
	private final LeafIconButton buttonSubmit = LeafIconButton.createButton( "Submeter plano de actua" + ccedil + atilde + "o", ICON_NAME_SUBMIT );

	private final AdicionarEquipamentosPanel panelEquipamentos = new AdicionarEquipamentosPanel();

	private final JTabbedPane tabs = new JTabbedPane();

	private final PlanoActuacaoPanel panelPlano = new PlanoActuacaoPanel();

	private final RelatorioLegislacoesPanel panelLegislacao = new RelatorioLegislacoesPanel();
	
	ButtonGroup bg = new ButtonGroup();

	private HsRelatorio relatorio = null;

	public PanelRelatorio()
	{
		setupListeners();
		startupComponents();
		startupLayout();
		placeComponents();
	}

	private void startupComponents()
	{
		dataRelatorio.setPreferredSize( new Dimension( 150, 0 ) );
		panelEquipamentos.setPreferredSize( new Dimension( 400, 0 ) );
		fieldFuncao1.setPreferredSize( new Dimension( 100, 0 ) );
		bg.add( radioInicial );
		bg.add( radioPeriodica );
		panelAcompanhantes.setBorder( BorderFactory.createTitledBorder( "Pessoas que acompanharam" ) );
		panelEquipamentos.setBorder( BorderFactory.createTitledBorder( "Equipamentos de medi"+ccedil+atilde+"o" ) );
		tabs.addTab( "Plano de actua" + ccedil + atilde + "o", panelPlano );
		tabs.addTab( "Legisla" + ccedil + atilde + "o", panelLegislacao );
	}

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

		layout = new TableLayout( new double[] {
				TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM, TableLayout.PREFERRED
		}, new double[] {
				TableLayout.MINIMUM, TableLayout.MINIMUM/*, TableLayout.MINIMUM*/
		} );
		layout.setVGap( 5 );
		layout.setHGap( 5 );
		panelAcompanhantes.setLayout( layout );
	}

	private void placeComponents()
	{
		panelAcompanhantes.add( new JLabel( "Nome" ), new TableLayoutConstraints( 0, 0 ) );
		panelAcompanhantes.add( fieldNome1, new TableLayoutConstraints( 1, 0 ) );
		panelAcompanhantes.add( new JLabel( "Fun" + ccedil + atilde + "o" ), new TableLayoutConstraints( 2, 0 ) );
		panelAcompanhantes.add( fieldFuncao1, new TableLayoutConstraints( 3, 0 ) );
		panelAcompanhantes.add( new JLabel( "Nome" ), new TableLayoutConstraints( 0, 1 ) );
		panelAcompanhantes.add( fieldNome2, new TableLayoutConstraints( 1, 1 ) );
		panelAcompanhantes.add( new JLabel( "Fun" + ccedil + atilde + "o" ), new TableLayoutConstraints( 2, 1 ) );
		panelAcompanhantes.add( fieldFuncao2, new TableLayoutConstraints( 3, 1 ) );
//		panelAcompanhantes.add( new JLabel( "Nome" ), new TableLayoutConstraints( 0, 2 ) );
//		panelAcompanhantes.add( fieldNome3, new TableLayoutConstraints( 1, 2 ) );
//		panelAcompanhantes.add( new JLabel( "Fun" + ccedil + atilde + "o" ), new TableLayoutConstraints( 2, 2 ) );
//		panelAcompanhantes.add( fieldFuncao3, new TableLayoutConstraints( 3, 2 ) );
		
		TableLayout layout = new TableLayout( new double[] {
				TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM
		}, new double[] {
				TableLayout.MINIMUM
		} );
		layout.setVGap( 5 );
		layout.setHGap( 5 );
		JPanel panel = new JPanel();
		panel.setLayout( layout );

		panel.add( buttonSave, new TableLayoutConstraints( 0, 0 ) );
		panel.add( buttonRevert, new TableLayoutConstraints( 1, 0 ) );
		panel.add( buttonSubmit, new TableLayoutConstraints( 3, 0 ) );
		
		add( panel, new TableLayoutConstraints( 0, 0, 7, 0 ) );
		add( new JLabel( "Data do relat" + oacute + "rio" ), new TableLayoutConstraints( 0, 1, 2, 1 ) );
		add( dataRelatorio, new TableLayoutConstraints( 3, 1 ) );
		JLabel labelAvaliacao = new JLabel( "Avalia" + ccedil + atilde + "o" );
		labelAvaliacao.setHorizontalAlignment( JLabel.RIGHT );
		add( labelAvaliacao , new TableLayoutConstraints( 4, 1 ) );
		add( radioInicial, new TableLayoutConstraints( 5, 1 ) );
		add( radioPeriodica, new TableLayoutConstraints( 6, 1 ) );
		add( new JLabel( "T" + eacute + "cnico Superior de H.S." ), new TableLayoutConstraints( 0, 2, 2, 2 ) );
		add( fieldTecnico, new TableLayoutConstraints( 3, 2, 6, 2 ) );
		add( panelEquipamentos, new TableLayoutConstraints( 7, 1, 7, 3 ) );
		add( panelAcompanhantes, new TableLayoutConstraints( 0, 3, 6, 3 ) );
		add( tabs, new TableLayoutConstraints( 0, 4, 7, 4 ) );
	}

	private void setupListeners()
	{
		fieldFuncao1.addCaretListener( this );
		fieldFuncao2.addCaretListener( this );
//		fieldFuncao3.addCaretListener( this );
		fieldNome1.addCaretListener( this );
		fieldNome2.addCaretListener( this );
//		fieldNome3.addCaretListener( this );
		dataRelatorio.addChangeListener( this );
		radioInicial.addActionListener( this );
		radioPeriodica.addActionListener( this );
		buttonSave.addActionListener( new ActionListener()
		{
			@Override
			public void actionPerformed( ActionEvent e )
			{
				save();
			}
		} );
		buttonRevert.addActionListener( new ActionListener()
		{
			@Override
			public void actionPerformed( ActionEvent e )
			{
				revert();
			}
		} );
		buttonSubmit.addActionListener( new ActionListener()
		{
			@Override
			public void actionPerformed( ActionEvent e )
			{
				if( isValidPlano() && JOptionPane.OK_OPTION == confirmSubmit() )
				{
					submit();
				}
			}
		} );
	}
	
	private boolean isValidPlano()
	{
		boolean result = false;
		result = panelPlano.isValidPlano();
		if( !result )
		{
			JOptionPane.showMessageDialog( this, "Todos os riscos devem ser preenchidos antes da submiss"+ atilde + "o do plano de actua" + ccedil + atilde+ "o!", "Erro", JOptionPane.ERROR_MESSAGE, null );
		}
		return result;
	}
	
	private int confirmSubmit()
	{
		return JOptionPane.showConfirmDialog( this, "Ao submeter o Plano de Actua"+ccedil+atilde+"o n"+atilde+"o ser"+aacute+" mais poss"+iacute+"vel alter"+aacute+"-lo. Deseja continuar?" );
	}
	
	private void submit()
	{
		try
		{
			if( relatorio != null )
			{
				relatorio.setIsSubmetido( new Date() );
				relatorio.save();
				refresh();
				setRelatorio( relatorio, false );
			}
		} catch( Exception e )
		{
			LeafError.error(e);
		}
	}
	
	private void save()
	{
		try
		{
			if( relatorio != null )
			{
				relatorio.setData( dataRelatorio.getDate() );
				relatorio.setAvaliacaoInicial( radioInicial.isSelected() );
	//			MarcacoesEstabelecimento marcacao = relatorio.getToHsMarcacoesEstabelecimento();
	//			if( marcacao != null )
	//			{
	//				MarcacoesTecnicosHst tecnico = marcacao.getToMarcacoesTecnicosHst();
	//				if( tecnico != null )
	//				{
	//					tecnico.setNome( fieldTecnico.getText() );
	//				}
	//			}
			}
			relatorio.setAcompanhante1( fieldNome1.getText() );
			relatorio.setAcompanhante2( fieldNome2.getText() );
//			relatorio.setAcompanhante3( fieldNome3.getText() );
			
			relatorio.setFuncaoAcompanhante1(fieldFuncao1.getText());
			relatorio.setFuncaoAcompanhante2(fieldFuncao2.getText());
//			relatorio.setFuncaoAcompanhante3(fieldFuncao3.getText());
			relatorio.save();
			refresh();
			buttonRevert.setEnabled( false );
			buttonSave.setEnabled( false );
		} catch( Exception e )
		{
			LeafError.error(e);
		}
	}
	
	private void revert()
	{
		refresh();
		buttonRevert.setEnabled( false );
		buttonSave.setEnabled( false );
	}

	private void refresh()
	{
		dataRelatorio.setDate( relatorio == null ? null : relatorio.getData() );
		if( relatorio == null || relatorio.getAvaliacaoInicial() == null )
		{
			bg.clearSelection();
		}
		else
		{
			radioInicial.setSelected( relatorio.getAvaliacaoInicial() );
			radioPeriodica.setSelected( !relatorio.getAvaliacaoInicial() );
		}
		String tecnicoName = null;
		if(relatorio != null)
		{
			MarcacoesEstabelecimento marcacao = relatorio.getToHsMarcacoesEstabelecimento();
			if( marcacao != null )
			{
				MarcacoesTecnicosHst tecnico = marcacao.getToMarcacoesTecnicosHst();
				if( tecnico != null )
				{
					tecnicoName = tecnico.getNome();
				}
			}
		}
		fieldTecnico.setText( tecnicoName );
		fieldNome1.setText( relatorio == null ? null : relatorio.getAcompanhante1() );
		fieldNome2.setText( relatorio == null ? null : relatorio.getAcompanhante2() );
//		fieldNome3.setText( relatorio == null ? null : relatorio.getAcompanhante3() );
		fieldFuncao1.setText( relatorio == null ? null : relatorio.getFuncaoAcompanhante1() );
		fieldFuncao2.setText( relatorio == null ? null : relatorio.getFuncaoAcompanhante2() );
//		fieldFuncao3.setText( relatorio == null ? null : relatorio.getFuncaoAcompanhante3() );
	}
	
	private void setEnabled()
	{
		boolean enabled = relatorio != null && relatorio.getIsSubmetido() == null;
		dataRelatorio.setEnabled( enabled );
		radioInicial.setEnabled( enabled );;
		radioPeriodica.setEnabled( enabled );
		fieldTecnico.setEnabled( false );
		fieldNome1.setEnabled( enabled );
		fieldNome2.setEnabled( enabled );
//		fieldNome3.setEnabled( enabled );
		fieldFuncao1.setEnabled( enabled );
		fieldFuncao2.setEnabled( enabled );
//		fieldFuncao3.setEnabled( enabled );
		buttonSubmit.setEnabled( enabled );
	}
	
	public void setRelatorio( HsRelatorio relatorio,boolean create )
	{
		this.relatorio = relatorio;
		buttonSave.setEnabled( false );
		buttonRevert.setEnabled( false );
		panelEquipamentos.setRelatorio( relatorio );
		panelPlano.setRelatorio( relatorio );
		if( create )
		{
			panelPlano.revert(false);
		}
		refresh();
		setEnabled();
	}
	
	private void updated( EventObject e )
	{
		Object source = e.getSource();
		if( source instanceof Component )
		{
			if( ( (Component) source).isEnabled() )
			{
				buttonSave.setEnabled( true );
				buttonRevert.setEnabled( true );
			}
		}
	}

	@Override
	public void caretUpdate( CaretEvent e )
	{
		updated(e);
	}
	
	@Override
	public void stateChanged( ChangeEvent e )
	{
		updated(e);
	}

	@Override
	public void actionPerformed( ActionEvent e )
	{
		updated(e);
	}

}
