package interfacing;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.event.TableModelEvent;
import javax.swing.event.TableModelListener;

import mapping.data.JobClassesTable;

/**
 * This is a TableModelListener class implemented as a listener to
 * jobClassesTable. It listens to the events triggered by the JTable in
 * JobClassesTableJPanel and acts accordingly.
 * 
 * @author Majd Kokaly
 * 
 */
public class JobClassesTableModelListener implements TableModelListener {
	/**
	 * This is the model (data class) that this listener controls.
	 * Refer to the Model/Controller/View (MVC)
	 */
	private JobClassesTable table;

	public JobClassesTableModelListener(JobClassesTable table) {
		this.setTable(table);
	}

	public JobClassesTable getTable() {
		return table;
	}

	public void setTable(JobClassesTable table) {
		this.table = table;
	}
	
	/**
	 * This method is invoked when the table is changed
	 */
	public void tableChanged(TableModelEvent e) {
		if (e.getColumn() == 1) { // executionTime
			long l = 0;
			try {
				OurDefaultTableModel model = (OurDefaultTableModel) e.getSource();
				l = Long.parseLong(((String) model.getValueAt(e.getFirstRow(), e.getColumn())).trim());
			} catch (NumberFormatException ex) {
				JOptionPane.showMessageDialog(new JFrame(), "Please insert a valid execution time.", "Error",
						JOptionPane.ERROR_MESSAGE);
				((OurDefaultTableModel) e.getSource()).setValueAt(String.valueOf(table.get(e.getFirstRow() + 1)
						.getexecutionTime()), e.getFirstRow(), e.getColumn());
				return;
			}

			table.get(e.getFirstRow() + 1).setexecutionTime(l);

		}
		if (e.getColumn() == 2) { // Arrival Rate
			double d = 0;
			try {
				OurDefaultTableModel model = (OurDefaultTableModel) e.getSource();
				d = Double.parseDouble(((String) model.getValueAt(e.getFirstRow(), e.getColumn())).trim());
			} catch (NumberFormatException ex) {
				JOptionPane.showMessageDialog(new JFrame(), "Please insert a valid arrival rate.", "Error",
						JOptionPane.ERROR_MESSAGE);
				((OurDefaultTableModel) e.getSource()).setValueAt(String.valueOf(table.get(e.getFirstRow() + 1)
						.getArrivalRate()), e.getFirstRow(), e.getColumn());
				return;
			}
			table.get(e.getFirstRow() + 1).setArrivalRate(d);
		}
	}
}
