/*
 * This file is part of the DistSim distributed simulation framework (client)
 * Copyright (C) 2007 Ulf Hermann
 *
 * 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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */
package brn.distsim.client;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import javax.swing.JOptionPane;
import javax.swing.JTabbedPane;

import brn.distsim.client.data.StudyTree;
import brn.distsim.client.tableModels.EditableTableModel;
import brn.distsim.client.tableModels.StudyTableModel;
import brn.distsim.client.ui.ClientFrame;
import brn.distsim.client.ui.DBPanel;


public class DBConnector implements ActionListener {

	private Client parent;

	private static Connection definitions;

	private static Connection results;

	public static Connection getDefinitions() {
		return definitions;
	}
	
	public static Connection getResults() {
		return results;
	}
	
	public DBConnector(Client parent) {
		this.parent = parent;
		EditableTableModel.reconnectButton(parent.getFrame().getDbPanel().getConnectButton(), this);
	}

	public void actionPerformed(ActionEvent arg0) {
		try {
			ClientFrame frame = parent.getFrame();
			DBPanel p = frame.getDbPanel();

			Class.forName("com.mysql.jdbc.Driver");
			definitions = DriverManager.getConnection("jdbc:mysql://"
					+ p.getDefHostTextField().getText() + "/"
					+ p.getDefDbTextField().getText(), p.getDefUserTextField()
					.getText(), new String(p.getDefPasswordField()
					.getPassword()));
			results = DriverManager.getConnection("jdbc:mysql://"
					+ p.getResHostTextField().getText() + "/"
					+ p.getResDbTextField().getText(), p.getResUserTextField()
					.getText(), new String(p.getResPasswordField()
					.getPassword()));
			
			new StudyTableModel(frame, new StudyTree(definitions, null), frame.getStudyPanel().getStudyTable());
			
			JTabbedPane workspace = frame.getWorkspacePane();
			workspace.setSelectedIndex(workspace.getSelectedIndex() + 1);
			p.getConnectButton().setEnabled(false);
		} catch (SQLException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage());
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
			JOptionPane.showMessageDialog(null, e.getMessage());
		}
	}

}
