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

import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import brn.distsim.client.DBConnector;
import brn.distsim.client.DefinitionsData;
import brn.distsim.client.data.Study;
import brn.distsim.client.data.StudyTree;
import brn.distsim.client.ui.ClientFrame;
import brn.distsim.client.ui.StudyPanel;


public class StudyTableModel extends EditableTableModel<StudyTree, Study>
		implements ListSelectionListener {

	private static final long serialVersionUID = 805655165709581688L;

	private PackagesTableModel packages;

	private String[] columnNames = { "id", "name", "version", "command" };

	public StudyTableModel(ClientFrame frame, StudyTree data, JTable subject) {
		super(frame, data, subject);
		StudyPanel panel = frame.getStudyPanel();
		packages = new PackagesTableModel(frame, panel.getPackagesTable());
		panel.getStudyTable().setModel(this);

		reconnectButton(panel.getCommitButton(), this);
		reconnectButton(panel.getCreateButton(), this);
		reconnectButton(panel.getRemoveButton(), this);
		reconnectButton(panel.getRollbackButton(), this);
		reconnectButton(panel.getSelectStudyButton(), this);

		JComboBox box = frame.getStudyPanel().getStudyNameComboBox();
		ActionListener[] listeners = box.getActionListeners();
		for (int i = 0; i < listeners.length; ++i) {
			box.removeActionListener(listeners[i]);
		}
		box.addActionListener(this);
		readData();
		subject.getSelectionModel().addListSelectionListener(this);
	}

	public int getColumnCount() {
		return 4;
	}

	public int getRowCount() {
		return data.size();
	}

	public String getColumnName(int col) {
		return columnNames[col];
	}

	public Object getValueAt(int row, int col) {
		Study study = data.get(row);
		switch (col) {
		case 0:
			return study.getId();
		case 1:
			return study.getName();
		case 2:
			return study.getVersion();
		case 3:
			return study.getCommand();
		default:
			return null;
		}

	}

	public boolean isCellEditable(int row, int col) {
		if (col == 3 && data.isInserted(row))
			return true;
		else
			return false;
	}

	protected boolean examineAction(ActionEvent e) throws SQLException {
		if (!super.examineAction(e)) {
			String command = e.getActionCommand();
			if (command.equals("display")) {

				if (data.isChanged()) {
					if (warn("save changes?")) {
						data.commit();
					}
				}

				String selected = (String) frame.getStudyPanel()
						.getStudyNameComboBox().getSelectedItem();

				data.loadFromDB(selected);
				if (selected != null && !names.contains(selected)
						&& !selected.equals("")) {
					super.insertData(createData());
					names.add(selected);
				}
				fireTableStructureChanged();
			}
		}
		return true;
	}

	@Override
	protected void connect(Study newData) {
		new DefinitionsData(frame, newData);
		new MonitorTableModel(frame, newData);
	}

	@Override
	protected Study createData() {
		JComboBox box = frame.getStudyPanel().getStudyNameComboBox();
		String name = (String) box.getSelectedItem();
		String version = JOptionPane.showInputDialog("initial Version");
		if (name == null || version == null)
			return null;
		else {
			box.addItem(name);
			return new Study(DBConnector.getDefinitions(), name, version, "");
		}
	}

	@Override
	protected Study cloneData(Study orig) {
		String version = JOptionPane.showInputDialog("new Version");
		if (version == null)
			return null;
		else {
			return orig.deepCopy(version);
			//return new Study(orig, version, orig.getCommand());
		}
	}

	@Override
	protected void readData() {
		try {
			names = StudyTree.getNames(DBConnector.getDefinitions());
			JComboBox box = frame.getStudyPanel().getStudyNameComboBox();
			Object selected = box.getSelectedItem();
			box.removeAllItems();
			box.addItem("");
			for (String item : names) {
				box.addItem(item);
			}
			box.setSelectedItem(selected);
			fireTableStructureChanged();
		} catch (SQLException e) {
			error(e);
		}
	}

	

	public void setValueAt(Object value, int row, int col) {
		Study old = data.get(row);
		Study newStudy = new Study(old, old.getVersion(), (String) value);
		data.set(row, newStudy);
	}

	public void valueChanged(ListSelectionEvent e) {
		if (e.getValueIsAdjusting())
			return;
		ListSelectionModel lsm = (ListSelectionModel) e.getSource();
		if (lsm.isSelectionEmpty()) {
			packages.clear();
		} else {
			int selectedRow = lsm.getMinSelectionIndex();
			packages.configure(data.get(selectedRow), data.isInserted(selectedRow));
		}
	}
	
	protected boolean remove(int pos) {
		try {
		if (pos < 0)
			return false;
		data.get(pos).loadFromDb();
		data.remove(pos);
		fireTableStructureChanged();
		return true;
		} catch (SQLException e) {
			error(e);
			return false;
		}
	}
}
