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.LeafError;
import leaf.ui.LeafIconButton;
import leaf.ui.TreeTools;
import siprp.database.cayenne.objects.HsEquipamentoMedico;
import siprp.database.cayenne.objects.HsRelatorio;
import siprp.database.cayenne.objects.HsRelatorioEquipamentoMedico;
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/equipamentos/add.png";

	private static final String ICON_NAME_REVERT = "siprp/higiene/gestao/equipamentos/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.MINIMUM, TableLayout.FILL
		}, new double[] {
			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
		}, new double[] {
				TableLayout.MINIMUM, TableLayout.MINIMUM, TableLayout.FILL
		} );
		layout.setHGap( 5 );
		layout.setVGap( 5 );
		panel.setLayout( layout );
		panel.add( buttonAdicionar, new TableLayoutConstraints( 0, 0 ) );
		panel.add( buttonRemover, new TableLayoutConstraints( 0, 1 ) );

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

	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();
				HsRelatorioEquipamentoMedico rel = object == null ? null : ((object instanceof HsRelatorioEquipamentoMedico) ? (HsRelatorioEquipamentoMedico) ((EquipamentoNode) object).getUserObject() : 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()
	{
		try
		{
			if( relatorio != null )
			{
				String equipamentoString = JOptionPane.showInputDialog( this, "Descri" + ccedil + atilde + "o", "Criar novo equipamento de medi" + ccedil + atilde + "o", JOptionPane.QUESTION_MESSAGE );
				if( equipamentoString != null )
				{
					HsEquipamentoMedico equipamento = new HsEquipamentoMedico();
					equipamento.setNome( equipamentoString );
					equipamento.save();
					HsRelatorioEquipamentoMedico rel = new HsRelatorioEquipamentoMedico();
					rel.setToHsRelatorio( relatorio );
					rel.setToHsEquipamentoMedico( equipamento );
					rel.save();
					refresh();
				}
			}
		} catch( Exception e )
		{
			e.printStackTrace();
		}
	}

	private void rem()
	{
		try
		{
			TreePath path = tree.getSelectionPath();
			if( path != null )
			{
				Object object = path.getLastPathComponent();
				if( object instanceof EquipamentoNode )
				{
					HsRelatorioEquipamentoMedico rel = ((HsRelatorioEquipamentoMedico) ((EquipamentoNode) object).getUserObject());
					rel.delete();
				}
			}
			refresh();
		} catch( Exception e )
		{
			LeafError.error(e);
		}
	}

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

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

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

}
