/**
 * 
 */
package cz.neubauer.tomas.hazardanalysis.model.tablemodels;

import java.util.ArrayList;

import javax.swing.table.AbstractTableModel;

import cz.neubauer.tomas.hazardanalysis.model.components.Component;
import cz.neubauer.tomas.hazardanalysis.viewcontroller.administration.AdminFrame;

/**
 * @author Tomáš Neubauer
 */
public class ComponentTableModel extends AbstractTableModel {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4881938620896518947L;

	private ArrayList<Component> data;

	private AdminFrame owner;

	private String[] columnNames = new String[] { "Název komponenty",
			"Umístění komponenty" };

	public ComponentTableModel(AdminFrame owner, ArrayList<Component> data) {
		this.owner = owner;
		this.data = data;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getColumnCount()
	 */
	@Override
	public int getColumnCount() {
		return 2;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getRowCount()
	 */
	@Override
	public int getRowCount() {
		return data.size();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.TableModel#getValueAt(int, int)
	 */
	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		Component currentComponent = data.get(rowIndex);
		switch (columnIndex) {
		case 0:
			return currentComponent.getName();
		case 1:
			return currentComponent.getLocation();
		default:
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.AbstractTableModel#setValueAt(java.lang.Object,
	 *      int, int)
	 */
	@Override
	public void setValueAt(Object value, int rowIndex, int columnIndex) {
		Component currentComponent = data.get(rowIndex);
		switch (columnIndex) {
		case 0:
			currentComponent.setName((String) value);
			currentComponent.saveToDB(owner.getConnection());
			fireTableDataChanged();
			break;
		case 1:
			currentComponent.setLocation((String) value);
			currentComponent.saveToDB(owner.getConnection());
			fireTableDataChanged();
			break;
		default:
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.AbstractTableModel#isCellEditable(int, int)
	 */
	@Override
	public boolean isCellEditable(int rowIndex, int columnIndex) {
		return columnIndex == 0 || columnIndex == 1;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.swing.table.AbstractTableModel#getColumnName(int)
	 */
	@Override
	public String getColumnName(int column) {
		return columnNames[column];
	}

	public ArrayList<Component> getData() {
		return data;
	}

	public void setData(ArrayList<Component> data) {
		this.data = data;
	}

}
