/*
 *  iReport  --  Visual designer for generating JasperReports Documents
 *  Copyright (C) 2002  Giulio Toffoli gt@businesslogic.it
 *
 *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 *  Giulio Toffoli
 *  Via T.Aspetti, 233
 *  35100 Padova ITALY
 *  gt@businesslogic.it
 */
package com.businesslogic.ireport.ui;

import com.businesslogic.ireport.*;
import java.util.*;
import com.ms.wfc.app.*;
import com.ms.wfc.core.*;
import com.ms.wfc.ui.*;
import com.ms.wfc.html.*;
import java.sql.*;

/**
 * Questa classe puņ accettare un numero variabile di parametri sulla riga
 * di comando. L'esecuzione del programma inizia con il metodo main(). Il costruttore
 * della classe non viene richiamato fino a quando un oggetto di tipo "DBConnectionForm"
 * non viene creato nel metodo main().
 */
public class DBConnectionForm extends Form
{
	public ConnectionEntry ce=null;
	public DBConnectionForm()
	{
		super();

		// Necessario per il supporto della finestra di progettazione form di Visual J++
		initForm();		

		ce = new ConnectionEntry();
		// TODO: aggiungere il codice del costruttore dopo la chiamata di initForm.
	}

	/**
	 * DBConnectionForm esegue l'overriding di dispose e quindi puņ svuotare
	 * l'elenco dei componenti.
	 */
	public void dispose()
	{
		super.dispose();
		components.dispose();
	}

	private void buttonSave_click(Object source, Event e)
	{
		// Fill DBConnectionEntry...
		if (editName.getText().trim().length() == 0)
		{
			MessageBox.show("The name is void !?\nIt's no good!");
			return;
		}
		
		ce.database = editDatabase.getText();
		ce.username = editUsername.getText();
		ce.password = editPassword.getText();
		ce.url = editURL.getText();
		ce.savepwd = checkBoxSavePwd.getChecked();
		ce.driverClass = (String)comboBox1.getText();
		ce.name = editName.getText();
		
		this.setDialogResult(DialogResult.OK);
	}
	
	public void setConnectionEntry(ConnectionEntry ce)
	{
		 editDatabase.setText(ce.database);
		 editUsername.setText(ce.username);
		 editPassword.setText(ce.password);
		 checkBoxSavePwd.setChecked(ce.savepwd);
		 comboBox1.setText(ce.driverClass);
		 editName.setText(ce.name);
		 editURL.setText(ce.url);
	}
	
	public void fillComboDrivers(Vector v)
	{
		if (v!= null)
		{
			Enumeration enum = v.elements();
			while (enum.hasMoreElements())
			{
				String drv = (String) enum.nextElement();
				comboBox1.addItem(drv);
			}
			if (comboBox1.getItemCount()>0)
				this.comboBox1.setSelectedIndex(0);
		}
	}

	private void comboBox1_selectedIndexChanged(Object source, Event e)
	{
		if (editURL.getText().trim().length() == 0)
		{
				button1_click(button1,e);
		}
	}

	private void button1_click(Object source, Event e)
	{
			if (((String)comboBox1.getText()).equalsIgnoreCase("org.gjt.mm.mysql.Driver"))
			{
				String url = "jdbc:mysql://localhost/";
				if (((String)editDatabase.getText()).trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("com.internetcds.jdbc.tds.Driver"))
			{
				String url = "jdbc:freetds:sqlserver://localhost/";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("com.microsoft.jdbc.sqlserver.SQLServerDriver"))
			{
				String url = "jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("sun.jdbc.odbc.JdbcOdbcDriver"))
			{
				String url = "jdbc:odbc:";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "DSNAME";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("com.ms.jdbc.odbc.JdbcOdbcDriver"))
			{
				String url = "jdbc:odbc:";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "DSNAME";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("oracle.jdbc.driver.OracleDriver"))
			{
				String url = "jdbc:oracle:thin:@localhost:1521:";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("COM.ibm.db2.jdbc.app.DB2Driver"))
			{
				String url = "jdbc:db2:";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("com.informix.jdbc.IfxDriver"))
			{
				String url = "jdbc:informix-sqli://localhost:port/";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				
				url += ":informixserver=SERVERNAME";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("com.sybase.jdbc2.jdbc.SybDriver"))
			{
				String url = "jdbc:sybase:Tds:localhost:2638";
				//if (editDatabase.getText().trim().length()>0)
				//	url += editDatabase.getText();
				//else
				//	url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("com.mysql.jdbc.Driver"))
			{
				String url = "jdbc:mysql://localhost/";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("com.merant.datadirect.jdbc.sqlserver.SQLServerDriver"))
			{
				String url = "jdbc:sqlserver://localhost:1433/";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
					else if (((String)comboBox1.getText()).equalsIgnoreCase("com.inet.tds.TdsDriver"))
			{
				String url = "jdbc:inetdae7:localhost:1433/";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("org.postgresql.Driver"))
			{
				String url = "jdbc:postgresql://localhost:5432/";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("org.hsqldb.jdbcDriver"))
			{
				String url = "jdbc:hsqldb:[PATH_TO_DB_FILES]/";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
			else if (((String)comboBox1.getText()).equalsIgnoreCase("COM.cloudscape.JDBCDriver "))
			{
				String url = "jdbc:cloudscape:/cloudscape/";
				if (editDatabase.getText().trim().length()>0)
					url += editDatabase.getText();
				else
					url += "MYDATABASE";
				editURL.setText(url);
			}
		this.setActiveControl(editURL );

	}



	private void buttonTest_click(Object source, Event e)
	{
		
			
		try {

			Class.forName((String)comboBox1.getText() ).newInstance();;
			Connection conn = DriverManager.getConnection(this.editURL.getText(),
			this.editUsername.getText(),
			this.editPassword.getText()); 
			Statement stmt = conn.createStatement();
			
		}catch (NoClassDefFoundError ex)
		{
			MessageBox.show("NoClassDefFoundError!!\nCheck your classpath!","Errore",MessageBox.ICONERROR);
			return;					
		} 
		catch (ClassNotFoundException ex)
		{
			MessageBox.show("ClassNotFoundError:\n"+ ex.getMessage() +"\n\nCheck your classpath!","Errore",MessageBox.ICONERROR);
			return;					
		} 
		catch (java.sql.SQLException ex)
		{
			MessageBox.show("SQL problems:\n"+ex.getMessage()+"\n"+this.editURL.getText() ,"Errore",MessageBox.ICONERROR);
			return;					
		} 
		catch (Exception ex)
		{
			MessageBox.show("General problem:\n"+ex.getMessage()+"\n\nControllare nome utente e password, e che il DBMS sia attivo!","Errore",MessageBox.ICONERROR);
			return;					
		}
		
		MessageBox.show("Connection tested succesfully!","",MessageBox.ICONINFORMATION);
	}

	private void comboBox1_measureItem(Object source, MeasureItemEvent e)
	{
		
	}

	/**
	 * NOTA: il seguente codice č richiesto dalla finestra di progettazione form 
	 * di Visual J++. Č possibile modificarlo con l'Editor di form.  Non modificarlo
	 * con l'Editor del codice.
	 */
	Container components = new Container();
	Label label1 = new Label();
	ComboBox comboBox1 = new ComboBox();
	Label label2 = new Label();
	Edit editURL = new Edit();
	Label label3 = new Label();
	Edit editUsername = new Edit();
	Label label4 = new Label();
	Edit editPassword = new Edit();
	Label label5 = new Label();
	Edit editDatabase = new Edit();
	Label label6 = new Label();
	GroupBox groupBox1 = new GroupBox();
	Button buttonTest = new Button();
	Button buttonClose = new Button();
	Button buttonSave = new Button();
	Label label7 = new Label();
	Edit editName = new Edit();
	Label label8 = new Label();
	CheckBox checkBoxSavePwd = new CheckBox();
	Label label9 = new Label();
	Button button1 = new Button();

	private void initForm()
	{
		this.setText("New/Modify connection...");
		this.setAutoScaleBaseSize(new Point(5, 13));
		this.setBorderStyle(FormBorderStyle.FIXED_TOOLWINDOW);
		this.setClientSize(new Point(390, 230));

		label1.setLocation(new Point(8, 36));
		label1.setSize(new Point(64, 16));
		label1.setTabIndex(14);
		label1.setTabStop(false);
		label1.setText("JDBC Driver");

		comboBox1.setLocation(new Point(72, 32));
		comboBox1.setSize(new Point(312, 21));
		comboBox1.setTabIndex(1);
		comboBox1.setText("comboBoxDriver");
		comboBox1.addOnMeasureItem(new MeasureItemEventHandler(this.comboBox1_measureItem));
		comboBox1.addOnSelectedIndexChanged(new EventHandler(this.comboBox1_selectedIndexChanged));

		label2.setLocation(new Point(8, 60));
		label2.setSize(new Point(56, 16));
		label2.setTabIndex(13);
		label2.setTabStop(false);
		label2.setText("JDBC URL");

		editURL.setLocation(new Point(72, 56));
		editURL.setSize(new Point(272, 20));
		editURL.setTabIndex(2);
		editURL.setText("");

		label3.setLocation(new Point(8, 108));
		label3.setSize(new Point(56, 16));
		label3.setTabIndex(12);
		label3.setTabStop(false);
		label3.setText("User name");

		editUsername.setLocation(new Point(72, 104));
		editUsername.setSize(new Point(156, 20));
		editUsername.setTabIndex(4);
		editUsername.setText("");

		label4.setLocation(new Point(8, 132));
		label4.setSize(new Point(56, 16));
		label4.setTabIndex(11);
		label4.setTabStop(false);
		label4.setText("Password");

		editPassword.setLocation(new Point(72, 128));
		editPassword.setSize(new Point(156, 20));
		editPassword.setTabIndex(5);
		editPassword.setText("");
		editPassword.setPasswordChar('*');

		label5.setLocation(new Point(8, 84));
		label5.setSize(new Point(56, 16));
		label5.setTabIndex(10);
		label5.setTabStop(false);
		label5.setText("Database");

		editDatabase.setLocation(new Point(72, 80));
		editDatabase.setSize(new Point(156, 20));
		editDatabase.setTabIndex(3);
		editDatabase.setText("");

		label6.setLocation(new Point(232, 84));
		label6.setSize(new Point(156, 16));
		label6.setTabIndex(15);
		label6.setTabStop(false);
		label6.setText("(Required only for DB browsing)");

		groupBox1.setLocation(new Point(8, 188));
		groupBox1.setSize(new Point(376, 4));
		groupBox1.setTabIndex(16);
		groupBox1.setTabStop(false);
		groupBox1.setText("");

		buttonTest.setLocation(new Point(152, 200));
		buttonTest.setSize(new Point(68, 24));
		buttonTest.setTabIndex(7);
		buttonTest.setText("&Test");
		buttonTest.addOnClick(new EventHandler(this.buttonTest_click));

		buttonClose.setLocation(new Point(300, 200));
		buttonClose.setSize(new Point(76, 24));
		buttonClose.setTabIndex(9);
		buttonClose.setText("&Cancel");
		buttonClose.setDialogResult(DialogResult.CANCEL);

		buttonSave.setLocation(new Point(224, 200));
		buttonSave.setSize(new Point(72, 24));
		buttonSave.setTabIndex(8);
		buttonSave.setText("&Save");
		buttonSave.addOnClick(new EventHandler(this.buttonSave_click));

		label7.setLocation(new Point(8, 8));
		label7.setSize(new Point(60, 16));
		label7.setTabIndex(17);
		label7.setTabStop(false);
		label7.setText("Name");

		editName.setLocation(new Point(72, 4));
		editName.setSize(new Point(312, 20));
		editName.setTabIndex(0);
		editName.setText("");

		label8.setFont(new Font("Microsoft Sans Serif", 7.0f, FontSize.POINTS, FontWeight.NORMAL, false, false, false, CharacterSet.DEFAULT, 0));
		label8.setLocation(new Point(8, 152));
		label8.setSize(new Point(372, 28));
		label8.setTabIndex(18);
		label8.setTabStop(false);
		label8.setText("ATTENTION! Password are stored in clear text. If you don\'t specify a password now, the program will ask you for one only when required, and will not save it!");

		checkBoxSavePwd.setLocation(new Point(316, 132));
		checkBoxSavePwd.setSize(new Point(16, 12));
		checkBoxSavePwd.setTabIndex(6);
		checkBoxSavePwd.setText("checkBox1");

		label9.setLocation(new Point(236, 132));
		label9.setSize(new Point(76, 16));
		label9.setTabIndex(19);
		label9.setTabStop(false);
		label9.setText("Save password");

		button1.setLocation(new Point(344, 56));
		button1.setSize(new Point(40, 20));
		button1.setTabIndex(20);
		button1.setTabStop(false);
		button1.setText("Wizard");
		button1.addOnClick(new EventHandler(this.button1_click));

		this.setNewControls(new Control[] {
							button1, 
							label9, 
							checkBoxSavePwd, 
							label8, 
							editName, 
							label7, 
							buttonSave, 
							buttonClose, 
							buttonTest, 
							groupBox1, 
							label6, 
							editDatabase, 
							label5, 
							editPassword, 
							label4, 
							editUsername, 
							label3, 
							editURL, 
							label2, 
							comboBox1, 
							label1});
	}

	/**
	 * Punto di ingresso principale per l'applicazione. 
	 *
	 * @param args Matrice di parametri passata all'applicazione
	 * tramite la riga di comando.
	 */
	public static void main(String args[])
	{
		Application.run(new DBConnectionForm());
	}
}
