/*
 *
 * Copyright (C) 17 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.*;
import javax.swing.tree.*;
import java.awt.*;
import java.awt.event.*;

import java.sql.*;
import jxtray.connection.JxtConnection;


import java.util.Vector;

import jxtray.Messages;
import jxtray.Jxtray;



public class JxtStructurePanel extends JPanel implements ItemListener, Runnable
{
	private JPanel pNorth;
	private JSplitPane splitPane;
	private JPanel pSouth;
	
	private JTree treeTable ;
	private DefaultMutableTreeNode rootNode = null;
	private DefaultMutableTreeNode recordNode = null;
	private DefaultMutableTreeNode sizeNode = null;
	private DefaultMutableTreeNode primkeyNode = null;
	
	private JxtComboBox comboCatalog = new JxtComboBox();
	private JxtComboBox comboSchema = new JxtComboBox();
	private JxtComboBox comboTable = new JxtComboBox();
	
	private JxtConnection connection;
	
	private long recordSize = 0;
	
	private Thread thread = null;
	
	public JxtStructurePanel(JxtConnection con, String catalog[], String schema[])
	{
		super(new BorderLayout(),true );
		
		recordNode = new DefaultMutableTreeNode(Jxtray.getLang("sql.recordnumber"));
		primkeyNode = new DefaultMutableTreeNode(Jxtray.getLang("sql.primarykey"));
		sizeNode = new DefaultMutableTreeNode(Jxtray.getLang("sql.recordsize"));
		
		connection = con;
		
		pNorth = new JPanel();
		splitPane = new JSplitPane();
		
		comboTable.setEditable(true);
		
		if ( catalog.length > 0 )
			comboCatalog = new JxtComboBox(catalog);
		else
		{
			comboCatalog = new JxtComboBox();
			comboCatalog.setVisible(false);
		}
		
		if ( schema.length > 0 )
			comboSchema = new JxtComboBox(schema);
		else
		{
			comboSchema = new JxtComboBox();
			comboSchema.setVisible(false);
		}	
		pNorth.add(comboCatalog);
		pNorth.add(comboSchema);
		pNorth.add(comboTable);
		
		pSouth = new JPanel(new BorderLayout(),true);

		this.add(pNorth,BorderLayout.NORTH);
		splitPane.setLeftComponent(new JScrollPane());
		splitPane.setRightComponent(new JScrollPane());
		splitPane.setDividerLocation(150);
		splitPane.setOneTouchExpandable(true);
		this.add(splitPane,BorderLayout.CENTER);
		
		try
		{
				comboTable.addItemListener(this);
				init();
		}
		catch( Exception e )
		{
			Messages.error("JxtStructurePanel.init() : "+ e);
		}
		
		// les listeners doivent absolument être ajouté après...
		comboCatalog.addItemListener(this);
		comboSchema.addItemListener(this);
		
		this.revalidate();
	}
	
	public void run()
	{
		
	}
	

	
	public void init() throws Exception
	{
			Vector v = connection.getTables((String)comboCatalog.getSelectedItem(),(String) comboSchema.getSelectedItem());
			for ( int i=0; i<v.size();i++)
				comboTable.addItem(v.elementAt(i));
	}
	
	public void itemStateChanged( ItemEvent e )
	{
		this.setCursor(new Cursor(Cursor.WAIT_CURSOR));
			/** Catalog has been changed */
			if ( e.getSource().equals(comboCatalog) || e.getSource().equals(comboSchema) )
			{
					try
					{
						comboTable.removeAllItems();
						//comboTable.removeItemListener(this);
						Vector v = connection.getTables((String)comboCatalog.getSelectedItem(),(String) comboSchema.getSelectedItem());
						for ( int i=0; i<v.size();i++)
							comboTable.addItem(v.elementAt(i));
							
						//comboTable.addItemListener(this);

						
					}
					catch ( Exception ex )
					{
							Messages.error("JxtStructurePanel.itemStateChanged() : " + ex);
					}
			}

			/** Table has been changed */
			else if ( e.getSource().equals(comboTable) )
			{
				try 
				{	
						getInfoTable();	
				}
				catch ( Exception ex )
				{
					Messages.error("JxtStructurePanel.itemStateChanged() : " + ex);
				}
			}
			this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
	}
	
	private void getInfoTable() throws Exception
	{
		
		recordNode = new DefaultMutableTreeNode(Jxtray.getLang("sql.recordnumber"));
		primkeyNode = new DefaultMutableTreeNode(Jxtray.getLang("sql.primarykey"));
		sizeNode = new DefaultMutableTreeNode(Jxtray.getLang("sql.recordsize"));		
		
		if ( comboTable.getItemCount() == 0 )
				return;
		//splitPane.removeAll();
		JTable table ;	
		String title[] = new String[4];
	    title[0] = Jxtray.getLang("table.name");
		title[1] = Jxtray.getLang("table.format");
		title[2] = Jxtray.getLang("table.length");
		title[3] = Jxtray.getLang("table.nullable");
		
		Vector v1 = new Vector();
		Vector v2 = new Vector();
		Vector v3 = new Vector();
		Vector v4 = new Vector();
		
		ResultSet res1 = null;
		//if (connection.getMetaData().supportsSchemasInTableDefinitions() )
			res1 = connection.getMetaData().getColumns((String) comboCatalog.getSelectedItem(),(String) comboSchema.getSelectedItem(),(String) comboTable.getSelectedItem(),"%");
		/*else 
			res1 = connection.getMetaData().getColumns((String) comboCatalog.getSelectedItem(),null,(String) comboTable.getSelectedItem(),"%");*/
		int columncount = res1.getMetaData().getColumnCount();
		recordSize = 0;							
		while ( res1.next() ) 
		{
			v1.add(res1.getString(4));
			v2.add(res1.getString(6));
			int length=res1.getInt(7);
			int dec=res1.getInt(9);
			if( dec > 0 )
				v3.add(length+","+dec);
			else
				v3.add(""+length);
			recordSize += length;
			recordSize += dec;
			v4.add(res1.getString(18));			
		}
		
		String val2[][] = new String[v1.size()][4];
		for ( int i=0; i < v1.size(); i++ )
		{
			val2[i][0] = (String) v1.elementAt(i);
			val2[i][1] = (String) v2.elementAt(i);
			val2[i][2] = (String) v3.elementAt(i);
			val2[i][3] = (String) v4.elementAt(i);
		}
		table = new JTable(val2,title);		
		
		
		int nb =-1;
		try
		{
		
			if (connection.getMetaData().supportsSchemasInDataManipulation() )
			{
				rootNode = new DefaultMutableTreeNode((String)comboSchema.getSelectedItem()+"."+(String)comboTable.getSelectedItem());
				res1 = connection.getConnection().createStatement().executeQuery("select count(*)as nb from "+(String)comboSchema.getSelectedItem()+"."+(String)comboTable.getSelectedItem());
			}
			else if (connection.getMetaData().supportsCatalogsInDataManipulation() )
			{
				rootNode = new DefaultMutableTreeNode((String)comboCatalog.getSelectedItem()+"."+(String)comboTable.getSelectedItem());
				res1 = connection.getConnection().createStatement().executeQuery("select count(*)as nb from "+(String)comboCatalog.getSelectedItem()+"."+(String)comboTable.getSelectedItem());
			}
			else
			{
				rootNode = new DefaultMutableTreeNode((String)comboTable.getSelectedItem());
				res1 = connection.getConnection().createStatement().executeQuery("select count(*) as nb from "+(String)comboTable.getSelectedItem());
			}
			
			if ( res1.next() )
			{
				nb = res1.getInt("nb");
			}
		}
		catch ( Exception e )
		{
		}
		
		if ( nb == 0)
			recordNode.add(new DefaultMutableTreeNode(Jxtray.getLang("sql.emptytable")));
		else if ( nb == 1)
			recordNode.add(new DefaultMutableTreeNode( nb + " " +Jxtray.getLang("sql.record")));
		else
			recordNode.add(new DefaultMutableTreeNode( nb + " " +Jxtray.getLang("sql.record")+"s"));
				
		sizeNode.add(new DefaultMutableTreeNode( recordSize +" bytes"));
		try
		{
		
		/** To retreive primary key... */
		if (connection.getMetaData().supportsSchemasInTableDefinitions() )
				res1 = connection.getMetaData().getPrimaryKeys((String)comboCatalog.getSelectedItem(),(String)comboSchema.getSelectedItem(),(String)comboTable.getSelectedItem());
		else
			res1 = connection.getMetaData().getPrimaryKeys((String)comboCatalog.getSelectedItem(),null,(String)comboTable.getSelectedItem());
		
		int cptKey = 0;

		while ( res1.next() )
		{
			primkeyNode.add(new DefaultMutableTreeNode( res1.getString(4)));
			cptKey++;
		}
		}
		catch ( Exception e )
		{
				System.err.println("JxtStructureTable : getPrimaryKey : "+ e );
		}
		rootNode.add(recordNode);
		rootNode.add(sizeNode);
		rootNode.add(primkeyNode);
		treeTable = new JTree(rootNode);
	
		splitPane.setLeftComponent(new JScrollPane(treeTable));
		extendTree();
		splitPane.setRightComponent(new JScrollPane(table));
		splitPane.setOneTouchExpandable(true);
		this.add(splitPane,BorderLayout.CENTER);
		
	}	
	
	private void extendTree()
	{
		for ( int i = 0; i < treeTable.getRowCount(); i++ )
		{
			treeTable.expandRow(i);
		}
		treeTable.repaint();
		treeTable.revalidate();
	}
	
}
