/*
 *
 * Copyright (C)  30-août-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;

import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JFrame;
import javax.swing.ImageIcon;
import javax.swing.JOptionPane;
import javax.swing.ScrollPaneLayout;
import javax.swing.WindowConstants;

import javax.swing.tree.DefaultTreeModel;

import java.awt.*;

import java.awt.event.WindowListener;
import java.awt.event.WindowEvent;

import org.xml.sax.ContentHandler;
import org.xml.sax.XMLReader;
import org.xml.sax.InputSource;
import org.xml.sax.helpers.XMLReaderFactory;

import jxtray.swing.JxtMenuBar;
import jxtray.swing.JxtJTree;
import jxtray.swing.TreeConnectionElement;
import jxtray.swing.TreeConnectionListener;

import jxtray.connection.JxtConnectionHandler;
import jxtray.connection.JxtConnection;

import java.io.File;


/**
 * This class represant the main frame
 */
public class JxtFrame extends JFrame  implements WindowListener
{
		/** Buttons panel */
		private JScrollPane pconnexion;		
		/** Content panel (connections) */
		private JTabbedPane ptabbed = new JTabbedPane();
	   /** Split Panel : center panel */
		private JSplitPane splitPane = new JSplitPane();
		/** Connection tree */	
		private JxtJTree treeConnection ;
		private TreeConnectionListener treeListener;
		private TreeConnectionElement rootNode = null;
		
		
		public JxtFrame()
		{
				try
				{
						swingInit();
						
				}
				catch ( Exception e )
				{
						Messages.error("swingInit() : " + e);
						e.printStackTrace();
				}
		}
		
		/**
		 * Initialize basic graphical components
		 * @throws Exception
		 * void
		 */
		private void swingInit() throws Exception
		{
				pconnexion = new JScrollPane();
				pconnexion.setLayout(new ScrollPaneLayout());			
				
				ptabbed = new JTabbedPane();
				ptabbed.setDoubleBuffered(true);
				connectionInit();
				pconnexion.getViewport().add(treeConnection);

			    this.getContentPane().add(splitPane,  BorderLayout.CENTER);
			
				splitPane.add(pconnexion, JSplitPane.LEFT);
				splitPane.setLastDividerLocation(175);
				splitPane.setOneTouchExpandable(true);
			    splitPane.setRightComponent(ptabbed);
				splitPane.setDividerLocation(175);
			   
				this.setTitle(Jxtray.getLang("mainframe.title")+ " - "+JxtrayConstants.VERSION );
				this.setJMenuBar(new JxtMenuBar(this)); // ajout du menu.
			    this.setSize(Toolkit.getDefaultToolkit().getScreenSize());
			    this.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
			    this.addWindowListener(this);
			    
				
				this.setIconImage((new ImageIcon(getClass().getResource("/images/icons/jxtray.png"))).getImage() );
				
	}
	
	/** Load all connections and create an entry in the tree */		
	private void connectionInit() throws Exception
	{
			rootNode = new TreeConnectionElement(Jxtray.getLang("tree.connection"),TreeConnectionElement.NODE_ROOT);
			DefaultTreeModel defaultTreeModel = new DefaultTreeModel(rootNode);
			treeConnection = new JxtJTree(defaultTreeModel);
			treeListener = new TreeConnectionListener(treeConnection,ptabbed,defaultTreeModel);
			XMLReader reader = XMLReaderFactory.createXMLReader(JxtrayConstants.XMLPARSER);
  		
			ContentHandler jtreeHandler = new  JxtConnectionHandler(defaultTreeModel,rootNode,Jxtray.getConnectionManager());
			reader.setContentHandler(jtreeHandler);
			//	ANALYSE
			InputSource inputSource = new InputSource("file:///"+Jxtray.HOME+"conf"+File.separator+"connections.xml");
			reader.parse(inputSource);
			treeConnection.addTreeConnectionListener(treeListener);
			
	}
	
	public void windowClosing(WindowEvent e)
	  {
				quit();
	  }
	  public void windowClosed(WindowEvent e) {}
	  public void windowIconified(WindowEvent e) {}
	  public void windowOpened(WindowEvent e) {}
	  public void windowDeiconified(WindowEvent e) {}
	  public void windowActivated(WindowEvent e) {}
	  public void windowDeactivated(WindowEvent e) {}
	  
	  public TreeConnectionListener getTreeConnectionListener() { return treeListener; }
	  
	  public void addNewConnection(JxtConnection con)
	  {
	  	    TreeConnectionElement newCon = new TreeConnectionElement( con.getName(),TreeConnectionElement.NODE_CONNECTION_CLOSE);
			newCon.add(new TreeConnectionElement( con.getDriverName(),TreeConnectionElement.NODE_DRIVER));
			newCon.add(new TreeConnectionElement( con.getJxtConnectionParam().getJdbcurl(),TreeConnectionElement.NODE_JDBCURL));
			newCon.add(new TreeConnectionElement( con.getJxtConnectionParam().getLogin(),TreeConnectionElement.NODE_USER));
			rootNode.add(newCon);
			treeListener.getModel().reload();
			treeListener.getModel().nodeStructureChanged(rootNode);
			treeConnection.revalidate();

	  }
	  
	  public void updateNodeLabel(String oldLabel, String newLabel)
	  {
	  		treeListener.changeLabel(oldLabel,newLabel,rootNode);
			Component tab[] = ptabbed.getComponents();
			for ( int i = 0; i < tab.length; i++)
			{
				
				// TODO : ce code ne marche pas, le nom de ne réaffiche pas. 
				if ( tab[i].getName().equals(oldLabel) )
				{
					tab[i].setName(newLabel);
					tab[i].repaint();
					ptabbed.revalidate();
					break;
				}
			}
	  }
	  
	  public void quit()
	  {
	  	Jxtray.getSQLHistoryCache().writeXMLFile();
	  	if ( "TRUE".equals(Jxtray.getProperty("confirm.quit").toUpperCase()) )
		{
		
			int ret = Messages.question(Jxtray.getLang("app.close") );
			if ( ret == JOptionPane.NO_OPTION )
				return;
			else if ( ret == JOptionPane.YES_OPTION )
			{
				Jxtray.getConnectionManager().closeAllConnections();
				
				System.exit(0);
			}
		}
		else
		{
			Jxtray.getConnectionManager().closeAllConnections();
			System.exit(0);

		}
		
		
	  }
	  
	/** Memory managment */  
	protected void finalize() throws Throwable
	{
	  super.finalize();
	  pconnexion = null;
	  ptabbed = null;
	  rootNode = null;
	  splitPane = null;
	  treeConnection = null;
	  treeListener = null;
	}
		
}
