 /*
 * Copyright (C) 05-janv.-2004  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.gui;


import javax.swing.*;
import javax.swing.border.*;
import javax.swing.event.*;

import java.awt.*;
import java.awt.event.*;

import java.sql.*;

import jxtray.Jxtray;
import jxtray.Messages;

import jxtray.connection.JxtConnectionParam;

import jxtray.connection.DriverInfo;
import jxtray.connection.JxtConnection;


import jxtray.swing.JxtList;
import jxtray.swing.JxtComboBox;
import jxtray.swing.JxtButton;
import jxtray.swing.JxtCheckBox;


public class ConnectionDialog extends JDialog implements ActionListener, ListSelectionListener, ItemListener
{
	
	private JPanel pNorth;
	private JPanel pData;
	private JSplitPane splitPane;
	
	private JxtList listCon ;
	
	private JxtButton bAdd = new JxtButton(new ImageIcon(getClass().getResource("/images/add.png")),Jxtray.getLang("action.add"),this,Jxtray.getLang("action.add"));
	private JxtButton bModify = new JxtButton(new ImageIcon(getClass().getResource("/images/edit.png")),Jxtray.getLang("action.modify"),this,Jxtray.getLang("action.modify"));
	private JxtButton bDelete = new JxtButton(new ImageIcon(getClass().getResource("/images/delete.png")),Jxtray.getLang("action.delete"),this,Jxtray.getLang("action.delete"));
	private JxtButton bOk = new JxtButton(new ImageIcon(getClass().getResource("/images/apply.png")),Jxtray.getLang("action.ok"),this,Jxtray.getLang("action.ok"));
	private JxtButton bCancel = new JxtButton(new ImageIcon(getClass().getResource("/images/cancel.png")),Jxtray.getLang("action.cancel"),this,Jxtray.getLang("action.cancel"));
	
	private JxtComboBox comboDriverName;

	private JTextField jtNom = new JTextField();
	private JTextField jtLogin = new JTextField();
	private JTextField jtHost = new JTextField();
	private JPasswordField jtPassword = new JPasswordField();
	private JTextField jtJdbcUrl = new JTextField();
	private JxtCheckBox chkPrompt;

	private JScrollPane scrollData = new JScrollPane();
	

	private Connection connection;
	
	private int mode =0;
	
	private final int ADD = 1;
	private final int MODIFY = 2;
	private final int DELETE = 3;
	private final int OK = 4;

	
	public ConnectionDialog(JFrame parent)
	{
		super(parent,Jxtray.getLang("dialog.connection.title"),true);
		this.getContentPane().setLayout( new BorderLayout());
		this.setSize(600,400);
		this.setResizable(false);	
		
		try
		{
			init();
		}
		catch( Exception e )
		{
			Messages.error("JxtConnectionDialog.init() : error : "+ e );
		}		
		
		pNorth = new JPanel();
		pData = new JPanel();
		pData.setLayout(new BoxLayout(pData,BoxLayout.Y_AXIS) );
		
		splitPane = new JSplitPane();
		splitPane.setOrientation(JSplitPane.HORIZONTAL_SPLIT);

		splitPane.setDividerLocation(190);

		bOk.setEnabled(false);
		pNorth.add(bAdd);
		pNorth.add(bModify);
		pNorth.add(bDelete);
		pNorth.add(bOk);
		pNorth.add(bCancel);

		pData.add(scrollData);
		
		JPanel panel = new JPanel(new BorderLayout());
		
		TitledBorder border = BorderFactory.createTitledBorder("");
		border.setTitleFont(Jxtray.getFont());		
		
		panel.setBorder(BorderFactory.createTitledBorder(null,Jxtray.getLang("connection.name"),TitledBorder.LEFT,TitledBorder.ABOVE_TOP,Jxtray.getFont()));
		panel.add(jtNom,BorderLayout.CENTER);
		pData.add(panel);
		
		panel = new JPanel(new BorderLayout());
		panel.setBorder(BorderFactory.createTitledBorder(null,Jxtray.getLang("connection.driver"),TitledBorder.LEFT,TitledBorder.ABOVE_TOP,Jxtray.getFont()));
		panel.add(comboDriverName,BorderLayout.CENTER);
		pData.add(panel);
		
		panel = new JPanel(new BorderLayout());
		panel.setBorder(BorderFactory.createTitledBorder(null,Jxtray.getLang("connection.host"),TitledBorder.LEFT,TitledBorder.ABOVE_TOP,Jxtray.getFont()));
		panel.add(jtHost,BorderLayout.CENTER);
		pData.add(panel);
		
		panel = new JPanel(new BorderLayout());
		panel.setBorder(BorderFactory.createTitledBorder(null,Jxtray.getLang("connection.jdbcurl"),TitledBorder.LEFT,TitledBorder.ABOVE_TOP,Jxtray.getFont()));
		panel.add(jtJdbcUrl,BorderLayout.CENTER);
		pData.add(panel);		
		
		panel = new JPanel(new BorderLayout());
		panel.setBorder(BorderFactory.createTitledBorder(null,Jxtray.getLang("connection.login"),TitledBorder.LEFT,TitledBorder.ABOVE_TOP,Jxtray.getFont()));
		panel.add(jtLogin,BorderLayout.CENTER);
		pData.add(panel);
		
		panel = new JPanel(new BorderLayout());
		panel.setBorder(BorderFactory.createTitledBorder(null,Jxtray.getLang("connection.password"),TitledBorder.LEFT,TitledBorder.ABOVE_TOP,Jxtray.getFont()));
		panel.add(jtPassword,BorderLayout.CENTER);
		pData.add(panel);
		
		panel = new JPanel(new BorderLayout());
		chkPrompt= new JxtCheckBox(Jxtray.getLang("connection.promptpassword"),"FALSE");
		chkPrompt.addItemListener(this);
		panel.add(chkPrompt,BorderLayout.CENTER);
		pData.add(panel);
		

		scrollData = new JScrollPane(pData);

		splitPane.setLeftComponent(new JScrollPane(listCon));
		splitPane.setRightComponent(scrollData);

		this.getContentPane().add(pNorth,BorderLayout.NORTH);
		this.getContentPane().add(splitPane,BorderLayout.CENTER);
		hideField(false);
		
		if (listCon.getComponentCount() > 0 )
		{
			if ( Jxtray.getConnectionManager().getAllConnectionName().length > 0 )
					listCon.setSelectedIndex(0);
		}
			
	}
	
	public void init() throws Exception
	{
		listCon = new JxtList(this,Jxtray.getConnectionManager().getAllConnectionName());
		comboDriverName = new JxtComboBox(Jxtray.getDriverCache().getAllDriverName());
		comboDriverName.addItemListener(this);
	}
	
	public void valueChanged(ListSelectionEvent e)
	{
			
			JxtConnection con = null;
			try
			{ 
					con = (JxtConnection) Jxtray.getConnectionManager().get((String)listCon.getSelectedValue());
			}
			catch( Exception ex ) 
			{
					Messages.error("JxtConnectionDialog.valueChanged() : exception : " + ex );
					System.err.println("JxtConnectionDialog.valueChanged() : exception : " + ex );
			}
			if ( con == null )
			{
					Messages.error("JxtConnectionDialog.valueChanged() : error occured : item not found ");
					return;
			}
			jtNom.setText(con.getName());
			comboDriverName.setSelectedItem(con.getDriverName());
			jtHost.setText(con.getJxtConnectionParam().getHost());
			jtJdbcUrl.setText(con.getJxtConnectionParam().getJdbcurl());
			jtLogin.setText(con.getJxtConnectionParam().getLogin());
			jtPassword.setText(con.getJxtConnectionParam().getPassword());
			chkPrompt.setSelected(con.getJxtConnectionParam().isPasswordPrompt());
			 
	}
	
	
	public void ok()
	{
		
		switch ( mode )
		{
			case ADD:
				if(  Messages.question(Jxtray.getLang("action.add")+" '" +  jtNom.getText()+ "' ?") == JOptionPane.YES_OPTION ) 
				{
					
					try 
					{
						
						if ( !check())
						{
							Messages.error(Jxtray.getLang("connection.error"));
							return;
						}
						if ( Jxtray.getConnectionManager().containsKey(jtNom.getText() ) )
						{
							Messages.error(Jxtray.getLang("connection.exists"));
							return;
						}	
						
						
						JxtConnectionParam param= new JxtConnectionParam();
						
						param.setName(jtNom.getText());
						param.setHost(jtHost.getText());
						param.setJdbcurl(jtJdbcUrl.getText());
						param.setLogin(jtLogin.getText()); 
						param.setPassword(new String(jtPassword.getPassword()));
						param.setPasswordPrompt(chkPrompt.isSelected());
						
						JxtConnection newCon = new JxtConnection(param,(String) comboDriverName.getSelectedItem());						
						
						Jxtray.getConnectionManager().put(jtNom.getText(),newCon);
						Jxtray.getConnectionManager().writeXMLFile();
						Jxtray.getMainFrame().addNewConnection(newCon);
					}
					catch( Exception e )
					{
							Messages.error("JxtConnectionDialog.ok() - 1 : exception : " + e );
							System.err.println("JxtConnectionDialog.ok() - 1 : exception : " + e );
					}
					

					mode = 0;
					clearField();
					enabledActionButton(true);
					bOk.setEnabled(false);
					hideField(false);
					listCon.setEnabled(true);

					
					if ( listCon.getComponentCount() > 0)
								listCon.removeAll();
					try
					{
						listCon.removeListSelectionListener(this);
						listCon.setListData(Jxtray.getConnectionManager().getAllConnectionName());
						listCon.addListSelectionListener(this);
					}
					catch( Exception e )
					{
							Messages.error("JxtConnectionDialog.ok() - 2 : exception : " + e );
							System.err.println("JxtConnectionDialog.ok() - 2 : exception : " + e );
					}
			
				}
				break;
			case MODIFY:
				if ( Messages.question(Jxtray.getLang("action.modify")+" '" +listCon.getSelectedValue()+ "' ?") == JOptionPane.YES_OPTION)
				{
					if ( !check())
					{
						Messages.error(Jxtray.getLang("connection.error"));
						return;
					}
					try
					{
						JxtConnection con = (JxtConnection) Jxtray.getConnectionManager().get((String) listCon.getSelectedValue());
						String oldName = (String) listCon.getSelectedValue();
						Jxtray.getConnectionManager().remove(oldName);
						con.getJxtConnectionParam().setName(jtNom.getText());
						con.setDriverName((String)comboDriverName.getSelectedItem());
						con.getJxtConnectionParam().setHost(jtHost.getText());
						con.getJxtConnectionParam().setJdbcurl(jtJdbcUrl.getText());
						con.getJxtConnectionParam().setLogin(jtLogin.getText());
						con.getJxtConnectionParam().setPassword(new String(jtPassword.getPassword()));
						con.getJxtConnectionParam().setPasswordPrompt(chkPrompt.isSelected());
						
						Jxtray.getConnectionManager().put(con.getName(),con);
						Jxtray.getMainFrame().updateNodeLabel(oldName,con.getName());
						Jxtray.getConnectionManager().writeXMLFile();
					}
					catch( Exception e )
					{
						Messages.error("DriverDialog.ok() - 1 : exception : " + e );
						System.err.println("DriverDialog.ok() - 1 : exception : " + e );
					}
					
					mode = 0;
					clearField();
					enabledActionButton(true);
					bOk.setEnabled(false);
					hideField(false);
					
					if ( listCon.getComponentCount() > 0)
						listCon.removeAll();
					try
					{
						listCon.removeListSelectionListener(this);
						listCon.setListData(Jxtray.getConnectionManager().getAllConnectionName());
						listCon.addListSelectionListener(this);
					}
					catch( Exception e )
					{
								Messages.error("JxtConnectionDialog.ok() - 2 : exception : " + e );
								System.err.println("JxtConnectionDialog.ok() - 2 : exception : " + e );
					}					
				}
				break;
				
			default: 
				break;
		}
		
		listCon.setEnabled(true);

		
	}		
	
	public void action()
	{
			switch ( mode )
			{
					case ADD:
						listCon.setEnabled(false);
						enabledActionButton(false);
						bOk.setEnabled(true);
						clearField();
						hideField(true);
						break;

					case DELETE:
						if ( listCon.getSelectedIndex() >=0 )
						{
							if(  Messages.question(Jxtray.getLang("action.delete")+" '"+listCon.getSelectedValue()+"' ?") == JOptionPane.YES_OPTION ) 
							{
								try
								{
									String toRemove = (String)listCon.getSelectedValue();
									Jxtray.getConnectionManager().remove(toRemove);
									if (  listCon.getComponentCount() > 0)
										listCon.removeAll();
									listCon.removeListSelectionListener(this);
									listCon.setListData(Jxtray.getConnectionManager().getAllConnectionName());
									listCon.addListSelectionListener(this);
									Jxtray.getConnectionManager().writeXMLFile();
									Jxtray.getMainFrame().getTreeConnectionListener().removeNode(toRemove);
									
								}
								catch ( Exception e ) 
								{
										System.err.println("JxtConnectionDialog.action()-delete : exception : " + e );
								}
							}
						}
						mode =0;
					clearField();
						break;
					case MODIFY:
						enabledActionButton(false);
						bOk.setEnabled(true);
						hideField(true);
						break;
					default:
						listCon.setEnabled(true);
						break;
			}
			
	}	
	public void actionPerformed( ActionEvent e )
	{
		if ( e.getActionCommand().equals(Jxtray.getLang("action.add")) )
		{
			mode = ADD;
			action();
		}
		else if ( e.getActionCommand().equals(Jxtray.getLang("action.modify")) )
		{
			mode = MODIFY;
			action();
		}
		else if ( e.getActionCommand().equals(Jxtray.getLang("action.delete")) )
		{
			mode = DELETE;
			action();
		}
		else if ( e.getActionCommand().equals(Jxtray.getLang("action.ok")) )
			ok();
		else if ( e.getActionCommand().equals(Jxtray.getLang("action.cancel")) )
			cancel();
	}

	public void clearField()
	{
			jtNom.setText("");
			jtLogin.setText("");
			jtJdbcUrl.setText("");
			jtPassword.setText("");
			jtHost.setText("");
			jtNom.requestFocus();
			chkPrompt.setSelected(false);
			try
			{
				DriverInfo drv = (DriverInfo) Jxtray.getDriverCache().get((String ) comboDriverName.getSelectedItem());
				if ( drv != null )
				jtJdbcUrl.setText(drv.getUrl());
			}
			catch( Exception ex )
			{
			}
			
			
	}

	public void hideField(boolean state)
	{
			jtNom.setEnabled(state);
			jtLogin.setEnabled(state);
			jtJdbcUrl.setEnabled(state);
			jtPassword.setEnabled(state);
			jtHost.setEnabled(state);
			comboDriverName.setEnabled(state); 
			chkPrompt.setEnabled(state);
			
	}
	
	public void cancel()
	{
			bOk.setEnabled(false);
			enabledActionButton(true);
			clearField();
			hideField(false);
			listCon.setEnabled(true);
	}

	public void enabledActionButton(boolean state)
	{
			bAdd.setEnabled(state);
			bModify.setEnabled(state);
			bDelete.setEnabled(state);
	}
	
	public void itemStateChanged ( ItemEvent e )
	{
		if ( e.getSource().equals(comboDriverName))
		{
			try
			{
				DriverInfo drv = (DriverInfo) Jxtray.getDriverCache().get((String ) comboDriverName.getSelectedItem());
				if ( mode == ADD || jtJdbcUrl.isEnabled())
					jtJdbcUrl.setText(drv.getUrl());
			}
			catch( Exception ex )
			{
				Messages.error("JxtConnectionDialog.itemStateChanged() : "+ ex);
			}
		}
		else if ( e.getSource().equals(chkPrompt))
		{
			if ( chkPrompt.isSelected())
			{
				jtPassword.setText(""); jtPassword.setEnabled(false);
			}
			else
			{
				jtPassword.setEnabled(true);
			}
		}
			
	}
	
	private boolean check()
	{
			if ( jtNom.getText().trim().length() == 0 )
				return false;
				
			return true;
	}


	
}
