/*
 *  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 java.io.*;
import com.ms.wfc.app.*;
import com.ms.wfc.core.*;
import com.ms.wfc.ui.*;
import com.ms.wfc.html.*;

/**
 * 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 "DBConnectionsForm"
 * non viene creato nel metodo main().
 */
public class DBConnectionsForm extends Form
{
	MainForm mf;
	public DBConnectionsForm(MainForm mf)
	{
		super();

		// Necessario per il supporto della finestra di progettazione form di Visual J++
		initForm();		
		this.mf = mf;
		
		Vector  v = mf.getConnectionEntries();
		Enumeration enum = v.elements();
		while (enum.hasMoreElements())
		{
			ConnectionEntry ce = (ConnectionEntry)enum.nextElement();
			DataListItem dli = new DataListItem(ce,ce.name,0);
			dli.setSubItem(0,ce.username);
			dli.setSubItem(1,ce.url);
			listViewConnections.addItem(dli);
		}
		
		// TODO: aggiungere il codice del costruttore dopo la chiamata di initForm.
	}

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

	private void buttonNewF_click(Object source, Event e)
	{	
		DBConnectionForm cf = new DBConnectionForm();
		cf.fillComboDrivers( getDrivers() );
		if (cf.showDialog() == DialogResult.OK)
		{
			// Create a new Item...
			ConnectionEntry ce = cf.ce;
			DataListItem dli = new DataListItem(ce,ce.name,0);
			dli.setSubItem(0,ce.username);
			dli.setSubItem(1,ce.url);
			listViewConnections.addItem(dli);
			saveConnections();
		}
		;
	}

	private void button2_click(Object source, Event e)
	{
		this.dispose();
	}

	private void buttonModF_click(Object source, Event e)
	{
		
		if (listViewConnections.getSelectedItems().length > 0)
		{
			DataListItem dli = (DataListItem)(listViewConnections.getSelectedItems()[0]);
			ConnectionEntry  f = (ConnectionEntry)dli.getData();
		
			DBConnectionForm ff = new DBConnectionForm();
			ff.fillComboDrivers( getDrivers() );
			
			ff.setConnectionEntry(f);
			if (ff.showDialog() == DialogResult.OK)
			{
				ConnectionEntry g = ff.ce;
				f.name = g.name;
				f.database = g.database;
				f.username = g.username;
				f.password = g.password;
				f.driverClass = g.driverClass;
				f.savepwd = g.savepwd;
				f.url = g.url;
				
				dli.setSubItem(0,f.username);
				dli.setSubItem(1,f.url);
				dli.setText( f.name);
				saveConnections();
			}
		}
		;
	}
	
	public Vector getDrivers()
	{
		Vector v = new Vector();
		v.addElement("org.gjt.mm.mysql.Driver");
		v.addElement("com.internetcds.jdbc.tds.Driver");
		v.addElement("com.microsoft.jdbc.sqlserver.SQLServerDriver");
		v.addElement("sun.jdbc.odbc.JdbcOdbcDriver");
		v.addElement("com.ms.jdbc.odbc.JdbcOdbcDriver");
		v.addElement("oracle.jdbc.driver.OracleDriver");
		v.addElement("COM.ibm.db2.jdbc.app.DB2Driver");
		v.addElement("com.informix.jdbc.IfxDriver");
		v.addElement("com.sybase.jdbc2.jdbc.SybDriver");
		v.addElement("com.mysql.jdbc.Driver");
		v.addElement("com.merant.datadirect.jdbc.sqlserver.SQLServerDriver");
		v.addElement("com.inet.tds.TdsDriver");
		v.addElement("org.postgresql.Driver");
		v.addElement("org.hsqldb.jdbcDriver");
		v.addElement("COM.cloudscape.JDBCDriver");
		
		for (int i=0; i< listViewConnections.getItemCount(); ++i)
		{
			DataListItem dli = (DataListItem)listViewConnections.getItem(i);
			String drv = ((ConnectionEntry)dli.getData()).driverClass;
			if (!v.contains(drv))
				v.addElement(drv);
		}
		
		return v;
	}

	public void saveConnections()
	{
		try {
			FileOutputStream fos = new FileOutputStream(mf.propfile_name);
			Properties p = new Properties();
			
			Enumeration enum = mf.connProperties.propertyNames();
			while (enum.hasMoreElements())
			{
				String name = (String)enum.nextElement();
				if  (!name.startsWith("CONN"))
					 p.put( name, mf.connProperties.get(name));
			}	
			
			for (int i=0; i<listViewConnections.getItemCount(); ++i)
			{
				ConnectionEntry ce =  (ConnectionEntry)((DataListItem)listViewConnections.getItem(i)).getData();
				ce.saveIntoProperties(p,i);
			}
			p.save( fos, "#Connection properties");
			fos.close();
			mf.connProperties = p;
		} catch (Exception ex)
		{
			MessageBox.show("Errore: "+ex.getMessage(),"",MessageBox.ICONERROR);
		}	
	}
	
	private void buttonDelF_click(Object source, Event e)
	{
		if (listViewConnections.getSelectedItems().length > 0)
		{
			DataListItem dli = (DataListItem)(listViewConnections.getSelectedItems()[0]);
			listViewConnections.removeItem(dli);
			saveConnections();
		}
	}

	/**
	 * 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();
	Panel panel1 = new Panel();
	Button button2 = new Button();
	Button buttonDelF = new Button();
	Button buttonModF = new Button();
	Button buttonNewF = new Button();
	ListView listViewConnections = new ListView();
	ColumnHeader columnHeader1 = new ColumnHeader();
	ColumnHeader columnHeader2 = new ColumnHeader();
	ColumnHeader columnHeader3 = new ColumnHeader();

	private void initForm()
	{
		// NOTA: questo form contiene informazioni relative alle risorse in
		// un file esterno. Non modificare il parametro di tipo String delle
		// chiamate alla funzione resources.getObject(). Ad esempio, non
		// modificare"foo1_location" nella seguente riga di codice,
		// nemmeno se il nome dell'oggetto Foo viene modificato: 
		//	 foo1.setLocation((Point)resources.getObject("foo1_location"));

		IResourceManager resources = new ResourceManager(this, "DBConnectionsForm");
		this.setText("JDBC Connections...");
		this.setAutoScaleBaseSize(new Point(5, 13));
		this.setClientSize(new Point(423, 179));
		this.setIcon((Icon)resources.getObject("this_icon"));

		panel1.setDock(ControlDock.RIGHT);
		panel1.setLocation(new Point(339, 0));
		panel1.setSize(new Point(84, 179));
		panel1.setTabIndex(0);
		panel1.setText("panel1");

		button2.setAnchor(ControlAnchor.BOTTOMRIGHT);
		button2.setLocation(new Point(4, 148));
		button2.setSize(new Point(76, 24));
		button2.setTabIndex(1);
		button2.setText("Close");
		button2.addOnClick(new EventHandler(this.button2_click));

		buttonDelF.setLocation(new Point(4, 52));
		buttonDelF.setSize(new Point(76, 24));
		buttonDelF.setTabIndex(2);
		buttonDelF.setText("Delete");
		buttonDelF.addOnClick(new EventHandler(this.buttonDelF_click));

		buttonModF.setFont(Font.DEFAULT_GUI);
		buttonModF.setLocation(new Point(4, 28));
		buttonModF.setSize(new Point(76, 24));
		buttonModF.setTabIndex(3);
		buttonModF.setText("Modify");
		buttonModF.addOnClick(new EventHandler(this.buttonModF_click));

		buttonNewF.setLocation(new Point(4, 4));
		buttonNewF.setSize(new Point(76, 24));
		buttonNewF.setTabIndex(0);
		buttonNewF.setText("New");
		buttonNewF.addOnClick(new EventHandler(this.buttonNewF_click));

		columnHeader1.setText("Connection name");
		columnHeader1.setWidth(131);

		columnHeader2.setText("Username");
		columnHeader2.setWidth(99);

		columnHeader3.setText("URL");
		columnHeader3.setWidth(99);

		listViewConnections.setDock(ControlDock.FILL);
		listViewConnections.setSize(new Point(339, 179));
		listViewConnections.setTabIndex(1);
		listViewConnections.setText("listView1");
		listViewConnections.setFullRowSelect(true);
		listViewConnections.setGridLines(true);
		listViewConnections.setView(ViewEnum.REPORT);
		listViewConnections.setColumns(new ColumnHeader[] {
									   columnHeader1, 
									   columnHeader2, 
									   columnHeader3});

		this.setNewControls(new Control[] {
							listViewConnections, 
							panel1});
		panel1.setNewControls(new Control[] {
							  buttonNewF, 
							  buttonModF, 
							  buttonDelF, 
							  button2});
	}

	/**
	 * 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 DBConnectionsForm(null));
	}
}
