package siprp.higiene.gestao.postos;

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

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.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

import leaf.ui.LeafButton;
import leaf.ui.LeafError;
import leaf.ui.TreeInserterDialog;
import leaf.ui.TreeTools;
import siprp.database.cayenne.objects.Estabelecimentos;
import siprp.database.cayenne.objects.HsPosto;
import siprp.database.cayenne.objects.HsPostoEstabelecimento;
import siprp.logic.HigieneSegurancaLogic;
import siprp.logic.node.AreaNode;
import siprp.logic.node.PostoNode;

public class AdicionarAreasPanel extends JPanel
{

	private static final long serialVersionUID = 1L;

	public static final String SELECTION_CHANGED = "SELECTION_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 Estabelecimentos estabelecimento = null;

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

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

	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 )
			{
				setEnabled();
				TreePath path = tree.getSelectionPath();
				Object object = path == null ? null : path.getLastPathComponent();
				HsPosto posto = object == null ? null : ((object instanceof PostoNode) ? (HsPosto) ((PostoNode) object).getUserObject() : null);
				firePropertyChange( SELECTION_CHANGED, null, posto );
			}
		} );
		buttonAdicionar.addActionListener( new ActionListener()
		{
			@Override
			public void actionPerformed( ActionEvent e )
			{
				add();
			}
		} );
		buttonRemover.addActionListener( new ActionListener()
		{
			@Override
			public void actionPerformed( ActionEvent e )
			{
				rem();
			}
		} );
	}

	private void add()
	{
		DefaultMutableTreeNode allPostos = HigieneSegurancaLogic.getAreasTree( estabelecimento.getToEmpresas() );
		TreeTools.removeAll( allPostos, HigieneSegurancaLogic.getPostosTree( estabelecimento ) );
		TreeInserterDialog dialog = new TreeInserterDialog( this, "Adicionar Postos de Trabalho", allPostos );
		save( dialog.getResult() );
		refresh();
	}

	private void save( DefaultMutableTreeNode toadd )
	{
		try
		{
			Object obj = toadd.getUserObject();
			if( obj instanceof HsPosto )
			{
				HsPostoEstabelecimento rel = new HsPostoEstabelecimento();
				rel.setToEstabelecimentos( estabelecimento );
				rel.setToHsPosto( (HsPosto) obj );
				rel.save();
			}
			else
			{
				for( int i = 0; i < toadd.getChildCount(); ++i )
				{
					save( (DefaultMutableTreeNode) toadd.getChildAt( i ) );
				}
			}
		} catch( Exception e )
		{
			LeafError.error( e );
		}
	}

	private void rem()
	{
		TreePath path = tree.getSelectionPath();
		if( path != null )
		{
			Object object = path.getLastPathComponent();
			if( object instanceof PostoNode )
			{
				HsPosto posto = ((HsPosto) ((PostoNode) object).getUserObject());
				remPosto( posto );
			}
			else if( object instanceof AreaNode )
			{
				for( int i = 0; i < ((AreaNode) object).getChildCount(); ++i )
				{
					PostoNode postoNode = (PostoNode) ((AreaNode) object).getChildAt( i );
					remPosto( (HsPosto) postoNode.getUserObject() );
				}
			}
		}
		refresh();
	}

	private void remPosto( HsPosto posto )
	{
		try
		{
			HsPostoEstabelecimento toDelete = null;
			for( HsPostoEstabelecimento rel : posto.getHsPostoEstabelecimentoArray() )
			{
				if( rel.getToEstabelecimentos().equals( estabelecimento ) )
				{
					toDelete = rel;
					break;
				}
			}
			if( toDelete != null )
			{
				toDelete.delete();
			}
		}
		catch( Exception e )
		{
			LeafError.error( e );
		}
	}

	private void setEnabled()
	{
		buttonAdicionar.setEnabled( estabelecimento != null );
		buttonRemover.setEnabled( tree.getSelectionCount() > 0 );
	}

	public void refresh()
	{
		root.removeAllChildren();
		if( estabelecimento != null )
		{
			TreeTools.merge( root, HigieneSegurancaLogic.getAreasTree( estabelecimento ) );
		}
		setEnabled();
		TreeTools.refreshTree( tree, root );
	}

	public void setEstabelecimento( Estabelecimentos estabelecimento )
	{
		this.estabelecimento = estabelecimento;
		refresh();
	}

}
