/*
 *
 * Copyright (C) 11-sept.-2003  Jean-Yves Beaujean 
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the Free
 * Software Foundation; either version 2 of the License, or (at your option)
 * any later version.
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
 * more details.
 * You should have received a copy of the GNU General Public License along with
 * this program; if not, write to the Free Software Foundation, Inc.,  59
 * Temple Place - Suite 330, Boston, MA 02111-1307, USA.

 * 
 */
package jxtray.swing;


import javax.swing.JTabbedPane;
import javax.swing.tree.*;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.event.TreeSelectionEvent;

import java.awt.Cursor;
import java.awt.Component;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import jxtray.Jxtray;
import jxtray.Messages;

import jxtray.util.UIUtilities;

import jxtray.connection.JxtConnection;

import jxtray.gui.ConnectionPropertiesDialog;

import javax.swing.JOptionPane;

public class TreeConnectionListener  implements TreeSelectionListener, MouseListener, TreeModelListener, ActionListener
{

	private JxtJTree tree;
	private JTabbedPane tabbedPane;
	private DefaultTreeModel model;
	
	
	public TreeConnectionListener(JxtJTree tree, JTabbedPane tabbedPane, DefaultTreeModel model)
	{
			this.tree = tree;
			this.tabbedPane = tabbedPane;
			this.model = model;
			
	}
	
	public void valueChanged(TreeSelectionEvent e )
	{
							
	}
	
	public DefaultTreeModel getModel()
	{
			return model;
	}
		
	public void mousePressed( MouseEvent e )
	{
		
		// Clic droit
		if ( e.getButton() == MouseEvent.BUTTON2 || e.getButton() == MouseEvent.BUTTON3)
		{
			
			TreeConnectionElement  currentNode = null;
			TreePath currentSelection = null;
			try
			{
				currentSelection = tree.getSelectionPath();
				currentNode = (TreeConnectionElement)
					(currentSelection.getLastPathComponent());
			}
			catch( Exception ex )
			{
			}
			
			if ( !currentNode.isRoot() && !currentNode.isLeaf() )
				tree.showPopupMenu((Component) e.getSource(),e.getX(),e.getY());
		}	
		else
		{	
			if ( e.getClickCount() > 1 )
			{
				
				openNewConnectionPanel();	 
				 
			}
		}
	}
	public void mouseEntered( MouseEvent e )  	{}		
	public void mouseExited( MouseEvent e )      	{}
	public void mouseClicked( MouseEvent e )		{}
	public void mouseReleased( MouseEvent e ) 	{}
	
	public void removeCurrentNode()
	  {
			TreePath currentSelection = tree.getSelectionPath();
			if (currentSelection != null)
			{
				DefaultMutableTreeNode currentNode = (DefaultMutableTreeNode)
							 (currentSelection.getLastPathComponent());
				MutableTreeNode parent = (MutableTreeNode)(currentNode.getParent());
				if (parent != null)
				{
					model.removeNodeFromParent(currentNode);
					return;
				}
			}
	  }
  
  
	  /** Supprime le noeud dont le label contient num */
	  public void removeNode(String label)
	  {
			DefaultMutableTreeNode precedent = (DefaultMutableTreeNode) model.getRoot();
			DefaultMutableTreeNode current = null;
			while ( true )
			{
             
				 current = precedent.getNextNode();
				 if ( current == null  )
					break;
				 if ( !current.isLeaf())
				 {
				 	try
					{
				 		String value = (String)current.getUserObject();
				 		if ( value.trim().equals(label.trim()) )
				 		{
							model.removeNodeFromParent(current);
							tree.revalidate();
				 		}
					}
				 	catch ( Exception ex )
					{
						System.err.println();
						Messages.error("TreeConnectionListener.removeNode() :  Exception : "+ ex );
						break;
					}
				 }
				precedent = current;
		   }
	  }


	  /** Remove the currently selected node. */
	  public void changeLabelCurrentNode(String newlabel, int type)
	  {
			TreePath currentSelection = tree.getSelectionPath();
			if (currentSelection != null)
			{
				TreeConnectionElement currentNode = (TreeConnectionElement)
							 (currentSelection.getLastPathComponent());
				currentNode.setUserObject(newlabel);
				currentNode.setType(type);
			}
	  }


	  public void treeNodesChanged( TreeModelEvent e)
	  {
	  }
	  public void treeNodesInserted( TreeModelEvent e)
	  {
	  }
	  public void treeNodesRemoved( TreeModelEvent e)
	  {
	  }
	  public void treeStructureChanged( TreeModelEvent e)
	  {
	  }
	  
	public void actionPerformed( ActionEvent e)
	{
			if ( e.getActionCommand().equals(Jxtray.getLang("action.close")))
			{
				closeConnectionPanel();
			}
			else if ( e.getActionCommand().equals(Jxtray.getLang("action.delete")))
			{
				deleteConnectionPanel();
			}
			else if ( e.getActionCommand().equals(Jxtray.getLang("action.open")))
			{
				openNewConnectionPanel();
			}
			else if ( e.getActionCommand().equals(Jxtray.getLang("action.properties")))
			{
				String connectionName = getSelectedConnectionName();
				try
				{
					JxtConnection _con = (JxtConnection) Jxtray.getConnectionManager().get(connectionName);
					if ( !_con.isConnected())
						return;
				
					ConnectionPropertiesDialog _diag = new ConnectionPropertiesDialog(Jxtray.getMainFrame(),_con.getProperties(),_con.getName());
					UIUtilities.center(_diag);
					_diag.setVisible(true);
				}
				catch ( Exception ex ) 
				{
					Messages.error(ex.getMessage());
				}
								
			}			
											
	}	  
	
	private void openNewConnectionPanel()
	{
			double t = System.currentTimeMillis();
			Jxtray.getMainFrame().setCursor(new Cursor(Cursor.WAIT_CURSOR));
			String connectionName = getSelectedConnectionName();
			if ( connectionName == null)
			{
				Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
				return;
			}
				
			JxtConnection con = (JxtConnection) Jxtray.getConnectionManager().get(connectionName);
			if ( !con.isVisible()    )
			{	
				Jxtray.getMainFrame().setCursor(new Cursor(Cursor.WAIT_CURSOR));
				try
				{
					if ( con.getJxtConnectionParam().isPasswordPrompt())
					{
						String password = PasswordBox.showPasswordBox(null,"Enter password", "Password for "+ con.getName()+ " :  login = "+ con.getJxtConnectionParam().getLogin());
						if ( password == null )
						{
							Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));	
							return;
						}
						con.getJxtConnectionParam().setPassword(password);
					}
					con.connect();
				}
				catch ( Exception ex )
				{
					Messages.error("Connection error : "+ ex );
					Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
					return;
				}
				tabbedPane.add(new JxtConnectionPanel( connectionName) );
				tabbedPane.setSelectedComponent(tabbedPane.getComponentAt(tabbedPane.getComponentCount()-1));
			
				changeLabelCurrentNode(connectionName, TreeConnectionElement.NODE_CONNECTION_OPEN);
				tree.repaint();
				Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
											
			}
				
		Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));	
		double diff = System.currentTimeMillis() - t;
		System.out.println("ConnectionPanel ["+connectionName+"] created : time :"+(diff/1000)+"sec.");			
	}
	
	private void closeConnectionPanel()
	{
		String connectionName = getSelectedConnectionName();
		Jxtray.getMainFrame().setCursor(new Cursor(Cursor.WAIT_CURSOR));
		if ( connectionName == null)
		{
			Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			return;
		}
				
		JxtConnection con = (JxtConnection) Jxtray.getConnectionManager().get(connectionName);
					
		if ( con.isVisible()    )
		{	
			try
			{
				con.close();
			}
			catch ( Exception ex )
			{
				Messages.error("Close error : "+ ex );
				Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
				return;
			}
		
			Component tab[] = tabbedPane.getComponents();
			for ( int i = 0; i < tab.length; i++)
			{
				if ( tab[i].getName().equals(connectionName) )
					tabbedPane.remove(i);
			}
			changeLabelCurrentNode(connectionName ,TreeConnectionElement.NODE_CONNECTION_CLOSE);
			tree.repaint();
			Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
											
		}
				
		Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));				
	}
  
	private void deleteConnectionPanel()
	{
		
		String connectionName = getSelectedConnectionName();
		int ret = Messages.question(Jxtray.getLang("action.delete")+ " '"+ connectionName+ "' ?" );
		if ( ret == JOptionPane.NO_OPTION )
				return;
			
		Jxtray.getMainFrame().setCursor(new Cursor(Cursor.WAIT_CURSOR));
		if ( connectionName == null)
		{
			Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			return;
		}
				
		JxtConnection con = (JxtConnection) Jxtray.getConnectionManager().get(connectionName);
		
		if ( con.isVisible())
		{
			Component tab[] = tabbedPane.getComponents();
			for ( int i = 0; i < tab.length; i++)
			{
				if ( tab[i].getName().equals(connectionName) )
					tabbedPane.remove(i);
			}
		}				
		try
		{	
			if ( con.isConnected() )
				con.close();
		}
		catch ( Exception ex )
		{
			Messages.error("Close error : "+ ex );
			Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
			return;
		}
		

		try
		{
			Jxtray.getConnectionManager().remove(connectionName);
			Jxtray.getConnectionManager().writeXMLFile();
			removeCurrentNode();
			tree.revalidate();
		}
		catch ( Exception e )
		{
			Messages.error("TreeConnectionListener.deleteConnectionPanel() :"+ e);
		}
		Jxtray.getMainFrame().setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
	} 
	
	private String getSelectedConnectionName()
	{
		TreeConnectionElement node = (TreeConnectionElement) tree.getLastSelectedPathComponent();
		if ( node.getType() == TreeConnectionElement.NODE_CONNECTION_CLOSE || node.getType() == TreeConnectionElement.NODE_CONNECTION_OPEN)
			return (String)node.getUserObject();
		else 
			return null;
	}
	
	public void changeLabel(String oldLabel, String newLabel, TreeConnectionElement root )
	  {
		 try
		 {	
  	 
		 	TreeConnectionElement precedent = root;
			while ( true )
			{
					TreeConnectionElement current = (TreeConnectionElement) precedent.getNextNode();
					if ( current == null )
						  break;
					try
					{
						if ( !current.isLeaf())
						{
						
							String value = (String)current.getUserObject();
							if ( value.trim().equals(oldLabel.trim()) )
							{
								current.setUserObject(newLabel);
								model.nodeChanged(current);
								tree.revalidate();
								break;
							}
						}
					}
					catch ( Exception ex )
					{
							System.err.println("Erreur TreeControler.changeLabel :  "+ ex );
					}
					precedent = current;
				}
		 }
		 catch( Exception e )
		 {
				System.err.println("TreeControler.changeLabel() : "+ e);
		 }
	  }	
	
	
	
}
