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

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

import javax.swing.JComboBox;

import brn.distsim.client.DBConnector;
import brn.distsim.client.data.Package;
import brn.distsim.client.ui.PackageDefinitionDialog;


public class PackageDefinition implements ActionListener {

	private PackageDefinitionDialog d;

	public void actionPerformed(ActionEvent a) {
		try {
			Connection db = DBConnector.getDefinitions();
			Object source = a.getSource();

			if (d == null || !d.isVisible()) {
				d = new PackageDefinitionDialog(Package.getNames(db));
				d.getDefineButton().addActionListener(this);
				d.getVersions().addActionListener(this);
				d.getNames().addActionListener(this);
				d.pack();
				d.setVisible(true);
			} else {
				String name = (String) d.getNames().getSelectedItem();
				String version = (String) d.getVersions().getSelectedItem();
				String arch = (String) d.getArchitectures().getSelectedItem();
				if (source == d.getNames()) {
					JComboBox versions = d.getVersions();
					versions.removeAllItems();
					List<String> nameVersions = Package.getVersions(db, name);
					for (String currentVersion : nameVersions) {
						versions.addItem(currentVersion);
					}
					versions.addItem("");
				} else if (source == d.getVersions()) {
					JComboBox archs = d.getArchitectures();
					archs.removeAllItems();
					List<String> versionArchs = Package.getArchitectures(db,
							name, version);
					for (String currentArch : versionArchs) {
						archs.addItem(currentArch);
					}
					archs.addItem("");
				} else if (source == d.getDefineButton()) {
					Package p = new Package(db, name, version, arch, d.getUrl());
					p.performDbInsert();
					String file = d.getLocalPath();
					if (file != null) {
						p.upload(file);
					}
				}
			}

		} catch (SQLException e) {
			AddRemoveTableModel.error(e);
		} catch (IOException e) {
			AddRemoveTableModel.error(e);
		}

	}
}
