package siprp.higiene.gestao.equipamentos;

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.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JOptionPane;
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.LeafDialog;
import leaf.ui.LeafIconButton;
import leaf.ui.TreeInserterDialog;
import leaf.ui.TreeTools;
import siprp.database.cayenne.objects.HsEquipamento;
import siprp.database.cayenne.objects.HsRelatorio;
import siprp.database.cayenne.objects.HsRelatorioEquipamento;
import siprp.logic.HigieneSegurancaLogic;
import siprp.logic.node.EquipamentoNode;

public class AdicionarEquipamentosPanel extends JPanel
{

	private static final long serialVersionUID = 1L;

	public static final String SELECTION_CHANGED = "SELECTION_CHANGED";

	private static final String ICON_NAME_SAVE = "siprp/higiene/gestao/add.png";

	private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/delete.png";

	private final LeafButton buttonAdicionar = LeafIconButton.createButton( ICON_NAME_SAVE );

	private final LeafButton buttonRemover = LeafIconButton.createButton( ICON_NAME_REVERT );

	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 HsRelatorio relatorio = null;

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

	private void startupComponents()
	{
		buttonAdicionar.setEnabled( false );
		buttonRemover.setEnabled( false );
		buttonAdicionar.setToolTipText( "Adicionar" );
		buttonRemover.setToolTipText( "Remover" );
		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.MINIMUM, TableLayout.FILL
		}, 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( 1, 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();
				DefaultMutableTreeNode node = path == null ? null : (DefaultMutableTreeNode)path.getLastPathComponent();
				Object obj = node == null ? null : node.getUserObject();
				HsRelatorioEquipamento rel = obj == null ? null : ((obj instanceof HsRelatorioEquipamento) ? (HsRelatorioEquipamento) obj : null);
				firePropertyChange( SELECTION_CHANGED, null, rel == null ? null : rel.getToHsRelatorio() );
			}
		} );
		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()
	{
		if( relatorio != null )
		{
			
			DefaultMutableTreeNode allEquipamentos = HigieneSegurancaLogic.getEquipamentosTree();
			TreeInserterDialog dialog = new TreeInserterDialog("Adicionar equipamento",allEquipamentos);
			DefaultMutableTreeNode result = dialog.getResult();
			if( result != null )
			{
				for( int i = 0; i < result.getChildCount(); ++i )
				{
					DefaultMutableTreeNode node = (DefaultMutableTreeNode) result.getChildAt( i );
					Object obj = node.getUserObject();
					if( obj instanceof HsEquipamento )
					{
						try
						{
							HsEquipamento equipamento = (HsEquipamento) obj;
							HsRelatorioEquipamento relEqui = new HsRelatorioEquipamento();
							relEqui.setHsEquipamento( equipamento.getId() );
							relEqui.setToHsRelatorio( relatorio );
							relEqui.setMarca( equipamento.getMarca() );
							relEqui.setModelo( equipamento.getModelo() );
							relEqui.setTipo( equipamento.getTipo() );
							relEqui.save();
						}
						catch (Exception e)
						{
							LeafDialog.error( e );
						}
					}
				}
			}
			refresh();
		}
	}

	private void rem()
	{
		try
		{
			TreePath path = tree.getSelectionPath();
			DefaultMutableTreeNode node = path == null ? null : (DefaultMutableTreeNode)path.getLastPathComponent();
			Object obj = node.getUserObject();
			HsRelatorioEquipamento rel = obj == null ? null : ((obj instanceof HsRelatorioEquipamento) ? (HsRelatorioEquipamento) obj : null);
			if( rel != null && confirmDelete() )
			{
				rel.delete();
				refresh();
			}
		}
		catch (Exception e)
		{
			LeafDialog.error( e );
		}
	}
	
	private boolean confirmDelete()
	{
		return JOptionPane.OK_OPTION == JOptionPane.showConfirmDialog(
				null, "Tem a certeza que deseja remover o equipamento seleccionado?",
				"Confirmar remo" + ccedil + atilde + "o",
				JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null );
	}

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

	public void refresh()
	{
		root.removeAllChildren();
		if( relatorio != null )
		{
			for( HsRelatorioEquipamento rel : relatorio.getHsRelatorioEquipamentoArray() )
			{
				root.add( new EquipamentoNode( rel ) );
			}
		}
		setEnabled();
		TreeTools.refreshTree( tree, root );
	}

	public void setRelatorio( HsRelatorio relatorio )
	{
		this.relatorio = relatorio;
		refresh();
	}

}
