package siprp.higiene.gestao.email;

import javax.swing.JOptionPane;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreePath;

import leaf.ui.LeafError;
import leaf.ui.TreeTools;
import siprp.database.cayenne.objects.Estabelecimentos;
import siprp.database.cayenne.objects.HsEmail;
import siprp.database.cayenne.objects.HsEmailEstabelecimento;
import siprp.higiene.gestao.AdicionarPanel;
import siprp.logic.HigieneSegurancaLogic;

public class AdicionarEmailsPanel extends AdicionarPanel
{

	private static final long serialVersionUID = 1L;
	
	private Estabelecimentos estabelecimento = null;
	
	public void setEstabelecimento( Estabelecimentos estabelecimento )
	{
		this.estabelecimento = estabelecimento;
		refresh();
		setEnabled();
	}

	@Override
	protected void add()
	{
		try
		{
			if( estabelecimento != null )
			{
				String emailString = JOptionPane.showInputDialog( this, "Email", "Adicionar novo Email", JOptionPane.QUESTION_MESSAGE );
				if( emailString != null )
				{
					HsEmail email = new HsEmail();
					email.setEmail( emailString );
					email.save();
					HsEmailEstabelecimento rel = new HsEmailEstabelecimento();
					rel.setToHsEmail( email );
					rel.setToEstabelecimento( estabelecimento );
					rel.save();
					refresh();
				}
			}
		}
		catch (Exception e)
		{
			LeafError.error( e );
		}
	}


	@Override
	protected void rem()
	{
		try
		{
			TreePath path = tree.getSelectionPath();
			if( path != null )
			{
				DefaultMutableTreeNode node = (DefaultMutableTreeNode) path.getLastPathComponent();
				if( node != null )
				{
					Object obj = node.getUserObject();
					if( obj instanceof HsEmailEstabelecimento )
					{
						((HsEmailEstabelecimento) obj).delete();
						refresh();
					}
				}
			}
		}
		catch (Exception e)
		{
			LeafError.error( e );
		}
	}

	@Override
	public void refresh()
	{
		root.removeAllChildren();
		TreeTools.merge( root, HigieneSegurancaLogic.getEmailsForEstabelecimento( estabelecimento ) );
		TreeTools.refreshTree( tree, root );
	}
	
	@Override
	protected void setEnabled()
	{
		buttonAdicionar.setEnabled( estabelecimento != null );
		buttonRemover.setEnabled( tree.getSelectionCount() > 0 );
	}
	
}
