package siprp.higiene.relatorio;

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

import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import leaf.ui.LeafButton;
import leaf.ui.LeafError;
import leaf.ui.TreeTools;
import siprp.database.cayenne.objects.HsRelatorioMedida;
import siprp.database.cayenne.objects.HsRelatorioPosto;
import siprp.database.cayenne.objects.HsRelatorioPostoMedida;
import siprp.database.cayenne.objects.HsRelatorioPostoRisco;
import siprp.database.cayenne.objects.HsRelatorioRisco;
import siprp.logic.HigieneSegurancaLogic;
import siprp.logic.node.MedidaRelatorioNode;
import siprp.logic.node.RiscoRelatorioNode;

public class GerirMedidasRelatorioPanel extends JPanel
{

	private static final long serialVersionUID = 1L;

	public static final String SELECTION_CHANGED = "RISCOS_SELECTION_CHANGED";

	public static final String VALUE_CHANGED = "VALUE_CHANGED";

	private final LeafButton buttonAdicionar = new LeafButton( "Adicionar" );

	private final LeafButton buttonRemover = new LeafButton( "Remover" );

	private final DefaultMutableTreeNode root = new DefaultMutableTreeNode();

	private final DefaultTreeModel model = new DefaultTreeModel( root );

	public final JTree tree = new JTree( model );

	private final JScrollPane scroll = new JScrollPane( tree );

	private HsRelatorioPosto posto = null;

	public GerirMedidasRelatorioPanel()
	{
		startupComponents();
		setupLayout();
		placeComponents();
		startupListeners();
	}

	private void startupComponents()
	{
		buttonAdicionar.setEnabled( false );
		buttonRemover.setEnabled( false );
		tree.setRootVisible( false );
		tree.getSelectionModel().setSelectionMode( TreeSelectionModel.SINGLE_TREE_SELECTION );
		tree.setCellRenderer( new DefaultTreeCellRenderer()
		{

			private static final long serialVersionUID = 1L;

			public Component getTreeCellRendererComponent( JTree pTree, Object pValue, boolean pIsSelected, boolean pIsExpanded, boolean pIsLeaf, int pRow, boolean pHasFocus )
			{
				super.getTreeCellRendererComponent( pTree, pValue, pIsSelected, pIsExpanded, pIsLeaf, pRow, pHasFocus );
				boolean highlight = false;
				Color highColor = null;
				Color lowColor = null;
				if( pValue instanceof RiscoRelatorioNode )
				{
					Object userObject = ((RiscoRelatorioNode) pValue).getUserObject();
					if( userObject instanceof HsRelatorioPostoRisco )
					{
						highlight = HigieneSegurancaLogic.isRelatorioRiscoPreenchido( (HsRelatorioPostoRisco) userObject );
						highColor = RelatorioHigieneSegurancaWindow.COLOR_RISCO_OK_SEL;
						lowColor = RelatorioHigieneSegurancaWindow.COLOR_RISCO_OK;
					}
				}
				else if( pValue instanceof MedidaRelatorioNode )
				{
					Object userObject = ((MedidaRelatorioNode) pValue).getUserObject();
					if( userObject instanceof HsRelatorioPostoMedida )
					{
						HsRelatorioPostoMedida medida = (HsRelatorioPostoMedida) userObject;
						if( medida.getIsPlanoActuacao() != null )
						{
							highlight = medida.getIsPlanoActuacao();
							highColor = RelatorioHigieneSegurancaWindow.COLOR_MEDIDA_OK_SEL;
							lowColor = RelatorioHigieneSegurancaWindow.COLOR_MEDIDA_OK;
						}
					}
				}
				if( highlight )
				{
					setOpaque( true );
					setBackground( pIsSelected ? highColor : lowColor );
				}
				else
				{
					setOpaque( false );
				}
				return (this);
			}
		} );
	}

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

	private void placeComponents()
	{
		JPanel panel = new JPanel();
		TableLayout layout = new TableLayout( new double[] {
				TableLayout.MINIMUM, TableLayout.FILL, TableLayout.MINIMUM
		}, new double[] {
			TableLayout.MINIMUM
		} );
		layout.setHGap( 5 );
		layout.setVGap( 5 );
		panel.setLayout( layout );
		panel.add( buttonAdicionar, new TableLayoutConstraints( 0, 0 ) );
		panel.add( buttonRemover, new TableLayoutConstraints( 2, 0 ) );

		add( panel, new TableLayoutConstraints( 0, 0 ) );
		add( scroll, new TableLayoutConstraints( 0, 1 ) );
	}

	private void startupListeners()
	{
		tree.getSelectionModel().addTreeSelectionListener( new TreeSelectionListener()
		{
			@Override
			public void valueChanged( TreeSelectionEvent e )
			{
				Object object = null;
				TreePath path = tree.getSelectionPath();
				if( path != null )
				{
					Object selection = path.getLastPathComponent();
					if( selection instanceof RiscoRelatorioNode )
					{
						object = selection == null ? null : ((RiscoRelatorioNode) selection).getUserObject();

					}
					else if( selection instanceof MedidaRelatorioNode )
					{
						object = selection == null ? null : ((MedidaRelatorioNode) selection).getUserObject();
					}
				}
				setEnabled();
				firePropertyChange( SELECTION_CHANGED, null, object );
			}
		} );
		buttonAdicionar.addActionListener( new ActionListener()
		{

			@Override
			public void actionPerformed( ActionEvent e )
			{
				add();

			}

		} );
		buttonRemover.addActionListener( new ActionListener()
		{

			@Override
			public void actionPerformed( ActionEvent e )
			{
				rem();

			}

		} );
	}

	private HsRelatorioPostoRisco getSelectedRisco()
	{
		HsRelatorioPostoRisco result = null;
		TreePath path = tree.getSelectionPath();
		if( path != null )
		{
			Object selection = path.getLastPathComponent();
			if( selection instanceof RiscoRelatorioNode )
			{
				result = selection == null ? null : (HsRelatorioPostoRisco) ((RiscoRelatorioNode) selection).getUserObject();
			}
		}
		return result;
	}

	private HsRelatorioPostoMedida getSelectedMedida()
	{
		HsRelatorioPostoMedida result = null;
		TreePath path = tree.getSelectionPath();
		if( path != null )
		{
			Object selection = path.getLastPathComponent();
			if( selection instanceof MedidaRelatorioNode )
			{
				result = selection == null ? null : (HsRelatorioPostoMedida) ((MedidaRelatorioNode) selection).getUserObject();
			}
		}
		return result;
	}

	private void add()
	{
		try
		{
			HsRelatorioPostoRisco postoRisco = getSelectedRisco();
			if( posto != null )
			{
				HsRelatorioMedida medida = new HsRelatorioMedida();
				medida.setDescription( "" );
				medida.setRequesitosLegais( "" );
				medida.setToHsRelatorioRisco( postoRisco.getToHsRelatorioRisco() );
				HsRelatorioPostoMedida rel = new HsRelatorioPostoMedida();
				rel.setToHsRelatorioMedida( medida );
				rel.setToHsRelatorioPosto( posto );
				rel.save();
			}
			refresh();
			setEnabled();
		} catch( Exception e )
		{
			LeafError.error( e );
		}
	}

	private void rem()
	{
		try
		{
			TreePath path = tree.getSelectionPath();
			if( path != null )
			{
				Object selection = path.getLastPathComponent();
				if( selection instanceof MedidaRelatorioNode )
				{
					HsRelatorioPostoMedida rel = selection == null ? null : (HsRelatorioPostoMedida) ((MedidaRelatorioNode) selection).getUserObject();
					rel.getToHsRelatorioMedida().delete();
					rel.delete();
				}
			}
			refresh();
			setEnabled();
		} catch( Exception e )
		{
			LeafError.error( e );
		}
	}

	private void setEnabled()
	{
		boolean add = false;
		boolean rem = false;
		if( posto != null )
		{
			if( posto.getToHsRelatorioArea() != null && posto.getToHsRelatorioArea().getToHsRelatorio() != null && posto.getToHsRelatorioArea().getToHsRelatorio().getIsSubmetido() == null )
			{
				add = true;
				rem = true;
			}
		}
		buttonAdicionar.setEnabled( add && getSelectedRisco() != null );
		buttonRemover.setEnabled( rem && getSelectedMedida() != null );
	}

	public void refresh()
	{
		root.removeAllChildren();
		if( posto != null )
		{
			for( HsRelatorioPostoRisco rel : posto.getHsRelatorioPostoRiscoArray() )
			{
				RiscoRelatorioNode node = new RiscoRelatorioNode( rel );
				HsRelatorioRisco risco = rel.getToHsRelatorioRisco();
				for( HsRelatorioMedida medida : risco.getHsRelatorioMedidaArray() )
				{
					for( HsRelatorioPostoMedida medidaRel : medida.getHsRelatorioPostoMedidaArray() )
					{
						node.add( new MedidaRelatorioNode( medidaRel ) );
					}
				}
				root.add( node );
			}
		}
		setEnabled();
		TreeTools.refreshTree( tree, root );
	}

	public void setPosto( HsRelatorioPosto posto )
	{
		this.posto = posto;
		refresh();
		setEnabled();
	}

}
