package interfacing;

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

import mapping.Mapper;

/**
 * 
 * An object from this class and an object from ServersProcessingRatesJPanel are
 * the view/controller of the he Processing Rates objects of Server objects.
 * 
 * @author Majd Kokaly
 * 
 */
public class ServersProcessingRatesTableModelListener implements TableModelListener {
	private Mapper mapper;
	private int serverID;

	public ServersProcessingRatesTableModelListener(Mapper mapper, int id) {
		this.setMapper(mapper);
		this.setServerID(id);
	}

	public Mapper getMapper() {
		return mapper;
	}

	public void setMapper(Mapper mapper) {
		this.mapper = mapper;
	}

	public int getServerID() {
		return serverID;
	}

	public void setServerID(int serverID) {
		this.serverID = serverID;
	}

	/**
	 * This method is invoked by the ServersProcessingRatesJPanel to notify this
	 * object that table has changed. The model classes are modified accordingly
	 * by this object.
	 */
	public void tableChanged(TableModelEvent e) {

		ProcessingRatesTableModel model = (ProcessingRatesTableModel) e.getSource();
		if (e.getColumn() == 1) { // Real
			double d = 0;
			try 
			{
				d = Double.parseDouble(((String) model.getValueAt(e.getFirstRow(), e.getColumn())).trim());
			} 
			catch (NumberFormatException ex) 
			{
				JOptionPane.showMessageDialog(new JFrame(), "Please insert a valid rate value.", "Error",
						JOptionPane.ERROR_MESSAGE);
				model.setValueAt(String.valueOf(this.getMapper().getRealRate(getServerID(), e.getFirstRow() + 1)), e
						.getFirstRow(), e.getColumn());
				return;
			}
			System.out.print("Server: " + this.getServerID() + "Class " + e.getFirstRow() + 1 + "rate " + d);
			this.getMapper().setRealRate(getServerID(), e.getFirstRow() + 1, d);
		}
		if (e.getColumn() == 2) { // Assumed
			double d = 0;
			try 
			{
				d = Double.parseDouble(((String) model.getValueAt(e.getFirstRow(), e.getColumn())).trim());
			} 
			catch (NumberFormatException ex) 
			{
				JOptionPane.showMessageDialog(new JFrame(), "Please insert a valid rate value.", "Error",
						JOptionPane.ERROR_MESSAGE);
				model.setValueAt(String.valueOf(this.getMapper().getAssumedRate(getServerID(), e.getFirstRow() + 1)), e
						.getFirstRow(), e.getColumn());
				return;
			}

			this.getMapper().setAssumedRate(getServerID(), e.getFirstRow() + 1, d);
		}
	}
}
