 /*
 * 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.gui;

import javax.swing.filechooser.FileFilter;
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.CustomFileFilter;
import jxtray.util.FileUtilities;

import jxtray.connection.DriverInfo;
import jxtray.swing.JxtButton;
import jxtray.swing.JxtList;


public class DriverDialog extends JDialog implements ActionListener, ListSelectionListener
{
	private JPanel pButton;
	private JPanel pData;
	private JSplitPane splitPane;
	private String oldDriverName = "";
	private JxtList listDriver;
	
	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 JxtButton bBrowse = new JxtButton(new ImageIcon(getClass().getResource("/images/fileopen.png")),Jxtray.getLang("action.browse"),this,Jxtray.getLang("action.browse"));

	private JTextField jtNom = new JTextField();
	private JTextField jtClassName = new JTextField();
	private JTextField jtJarFileName = new JTextField();
	private JTextField jtWebsite = new JTextField();
	private JTextField jtJdbcUrl = new JTextField();

	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 DriverDialog(JFrame parent)
	{
		
		super(parent,Jxtray.getLang("dialog.driversjdbc.title"),true);
		this.getContentPane().setLayout( new BorderLayout());
		this.setSize(600,300);
		this.setResizable(false);	
		
		pButton = 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);

		pButton.add(bAdd);
		pButton.add(bModify);
		pButton.add(bDelete);
		pButton.add(bOk);
		pButton.add(bCancel);

		pData.add(scrollData);
		
		JPanel panel = new JPanel(new BorderLayout());
		panel.setBorder(BorderFactory.createTitledBorder(null,Jxtray.getLang("driver.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("driver.classname"),TitledBorder.LEFT,TitledBorder.ABOVE_TOP,Jxtray.getFont()));
		panel.add(jtClassName,BorderLayout.CENTER);	
		pData.add(panel);		
		
		panel = new JPanel(new BorderLayout());
		panel.setBorder(BorderFactory.createTitledBorder(null,Jxtray.getLang("driver.jarfile"),TitledBorder.LEFT,TitledBorder.ABOVE_TOP,Jxtray.getFont()));
		panel.add(jtJarFileName,BorderLayout.CENTER);	
		panel.add(bBrowse,BorderLayout.EAST);
		pData.add(panel);				
		
		panel = new JPanel(new BorderLayout());
		panel.setBorder(BorderFactory.createTitledBorder(null,Jxtray.getLang("driver.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("driver.website"),TitledBorder.LEFT,TitledBorder.ABOVE_TOP,Jxtray.getFont()));
		panel.add(jtWebsite,BorderLayout.CENTER);	

		pData.add(panel);		
		

		scrollData = new JScrollPane(pData);
		
		try
		{
			listDriver = new JxtList(this,Jxtray.getDriverCache().getAllDriverName());
		}
		catch( Exception e )
		{
			Messages.error("DriverDialog.init() : error : "+ e );
		}
		// les listeners doivent absolument être ajouté après...
		splitPane.setLeftComponent(new JScrollPane(listDriver));
		splitPane.setRightComponent(scrollData);

		this.getContentPane().add(pButton,BorderLayout.NORTH);
		this.getContentPane().add(splitPane,BorderLayout.CENTER);
		hideField(false);
		
		if (listDriver.getComponentCount() > 0 )
			listDriver.setSelectedIndex(0); 
			
	}
	
	public void valueChanged(ListSelectionEvent e)
	{
			DriverInfo drv = null;
			String value = (String)listDriver.getSelectedValue();
			if ( value == null )
			{
				Messages.error("DriverDialog.valueChanged() : Item not found [object is null]");
				return;
			} 
			try
			{ 
				drv = (DriverInfo) Jxtray.getDriverCache().get(value);
				if ( drv == null )
				{
						Messages.error("DriverDialog.valueChanged() : Item not found [object is null]");
						return;
				}
				oldDriverName = drv.getName();
				jtNom.setText(drv.getName());
				jtJdbcUrl.setText(drv.getUrl());
				jtWebsite.setText(drv.getWebsite());
				jtJarFileName.setText(drv.getPathfile() );
				jtClassName.setText(drv.getClassname());
			}
			catch( Exception ex ) 
			{
				Messages.error("DriverDialog.valueChanged() : " + ex );
				System.err.println("DriverDialog.valueChanged() : " + ex );
			}
			 
	}
	
	
	public void ok()
	{
		
		switch ( mode )
		{
			case ADD:
				String newDriverName = jtNom.getText();
				if(  Messages.question(Jxtray.getLang("action.add")+" '"+ newDriverName +"' ?") == JOptionPane.YES_OPTION ) 
				{

					try
					{
						if ( !check())
						{
							Messages.error(Jxtray.getLang("driver.error"));
							return;
						}
						if ( Jxtray.getDriverCache().contains(newDriverName))
						{
							Messages.error(Jxtray.getLang("driver.exists"));
							return;
						}
						DriverInfo drv= new DriverInfo();
						drv.setName(newDriverName);
						drv.setClassname(jtClassName.getText());
						drv.setUrl(jtJdbcUrl.getText());
						drv.setWebsite(jtWebsite.getText());
						drv.setPathfile(jtJarFileName.getText());
						Jxtray.getDriverCache().put(newDriverName,drv);
						Jxtray.getDriverCache().writeXMLFile();
					}
					catch( Exception e )
					{
						Messages.error("DriverDialog.ok() CASE ADD : exception : " + e );
						System.err.println("DriverDialog.ok() CASE ADD : exception : " + e );
					}
					

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

					
					if ( listDriver.getComponentCount() > 0)
								listDriver.removeAll();
					try
					{
						listDriver.removeListSelectionListener(this);
						listDriver.setListData(Jxtray.getDriverCache().getAllDriverName());
						listDriver.addListSelectionListener(this);
					}
					catch( Exception e )
					{
						Messages.error("DriverDialog.ok() CASE ADD 2 : exception : " + e );
						System.err.println("DriverDIalog.ok() CASE ADD 2: exception : " + e );
					}
			
				}
				break;
			case MODIFY:
				if ( Messages.question(Jxtray.getLang("action.modify")+" '"+ listDriver.getSelectedValue()+ "' ?") == JOptionPane.YES_OPTION)
				{
					
					if ( !check())
					{
						Messages.error(Jxtray.getLang("driver.error"));
						return;
					}
					try
					{
						DriverInfo drv= (DriverInfo) Jxtray.getDriverCache().get((String) listDriver.getSelectedValue());
						Jxtray.getDriverCache().remove(drv.getName());
						drv.setName(jtNom.getText());
						drv.setClassname(jtClassName.getText());
						drv.setUrl(jtJdbcUrl.getText());
						drv.setWebsite(jtWebsite.getText());
						drv.setPathfile(jtJarFileName.getText());
					
						Jxtray.getDriverCache().update(drv);
						Jxtray.getDriverCache().writeXMLFile();
						
						System.out.println("OldDriverName = "+oldDriverName );
						System.out.println("NewDriverName = "+jtNom.getText() );
						System.out.println("==================================" );
						Jxtray.getConnectionManager().updateDriverName(oldDriverName,jtNom.getText());
						Jxtray.getConnectionManager().writeXMLFile();
						Jxtray.getDriverCache().printState();
						Jxtray.getConnectionManager().printState();
						
						System.out.println("==================================" );
					}
					catch( Exception e )
					{
							Messages.error("DriverDialog.ok() - 1 : exception : " + e );
							System.err.println("DriverDialog.ok() - 1 : exception : " + e );
					}
					

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

					
					if ( listDriver.getComponentCount() > 0)
								listDriver.removeAll();
					try
					{
						listDriver.removeListSelectionListener(this);
						listDriver.setListData(Jxtray.getDriverCache().getAllDriverName());
						listDriver.addListSelectionListener(this);
					}
					catch( Exception e )
					{
							Messages.error("DriverDialog.ok() - 2 : exception : " + e );
							System.err.println("DriverDIalog.ok() - 2 : exception : " + e );
					}								
				}
				break;
			default: 
				break;
		}
		
		listDriver.setEnabled(true);
		
	}		
	
	public void action()
	{
			switch ( mode )
			{
					case ADD:
						enabledActionButton(false);
						listDriver.setEnabled(false);
						bOk.setEnabled(true);
						clearField();
						hideField(true);
						listDriver.setEnabled(false);
						break;

					case DELETE:
						if ( listDriver.getSelectedIndex() >=0 )
						{
							if(  Messages.question(Jxtray.getLang("action.delete")+" '"+listDriver.getSelectedValue()+"' ?") == JOptionPane.YES_OPTION ) 
							{
								try
								{
									Jxtray.getDriverCache().remove((String)listDriver.getSelectedValue());
									if (  listDriver.getComponentCount() > 0)
										listDriver.removeAll();
									listDriver.removeListSelectionListener(this);
									listDriver.setListData(Jxtray.getDriverCache().getAllDriverName());
									listDriver.addListSelectionListener(this);
									Jxtray.getDriverCache().writeXMLFile();
								}
								catch ( Exception e ) 
								{
										System.err.println("DriverDialog.action() : exception : " + e );
								}
							}
						}
						mode =0;
						clearField();
						break;
					case MODIFY:
						enabledActionButton(false);
						bOk.setEnabled(true);
						hideField(true);
						break;
					default:
						listDriver.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.browse")) )
		{
				CustomFileFilter zipfileFilter[] = {new CustomFileFilter(Jxtray.getLang("file.zip"),FileUtilities.ZIP),new CustomFileFilter(Jxtray.getLang("file.gzip"),FileUtilities.GZIP),new CustomFileFilter(Jxtray.getLang("file.jar"),FileUtilities.JAR)};
				String file = this.chooseFile(zipfileFilter) ;
				if ( file != null )
					jtJarFileName.setText(file);
		}
		else if ( e.getActionCommand().equals(Jxtray.getLang("action.modify")) )
		{
			if ( listDriver.getSelectedIndex() >= 0 )
			{
				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()
	{
			oldDriverName ="";
			jtNom.setText("");
			jtClassName.setText("");
			jtJdbcUrl.setText("");
			jtWebsite.setText("");
			jtJarFileName.setText("");
			jtNom.requestFocus();
	}

	public void hideField(boolean state)
	{
			jtNom.setEnabled(state);
			jtClassName.setEnabled(state);
			jtJdbcUrl.setEnabled(state);
			jtWebsite.setEnabled(state);
			jtJarFileName.setEnabled(state);
			bBrowse.setEnabled(state);
	}
	
	public void cancel()
	{
			bOk.setEnabled(false);
			enabledActionButton(true);
			clearField();
			hideField(false);
			listDriver.setEnabled(true);
	}

	public void enabledActionButton(boolean state)
	{
			bAdd.setEnabled(state);
			bModify.setEnabled(state);
			bDelete.setEnabled(state);
			
	}
	
	private boolean check()
	{
			if ( jtNom.getText().trim().length() == 0 )
				return false;
				
			return true;
	}	
	
	
		private static String chooseFile(CustomFileFilter fileFilter[] ) 
		{
				
			JFileChooser fileChooser = new JFileChooser();
			fileChooser.setAcceptAllFileFilterUsed(false);

			for ( int i =0; i < fileFilter.length;i++)
				fileChooser.setFileFilter(fileFilter[i]);
			
			boolean canWrite = true;
			canWrite = true;
			int ret = fileChooser.showOpenDialog(null);
			if ( ret == JFileChooser.APPROVE_OPTION)
			{
					StringBuffer name = new StringBuffer();
					String extension = ((CustomFileFilter)fileChooser.getFileFilter()).getExtension();
					
					try {name.append(fileChooser.getSelectedFile().getCanonicalPath());	}
					catch ( Exception ex )	
					{	Messages.error("Messages.chooseFile : " +ex );}
					
					if ( name.toString().toLowerCase().lastIndexOf("."+extension.toLowerCase()) <= 0)
						name.append("."+extension.toLowerCase());	

					return name.toString();
				}
				else
					return null;
		}


	
}
