package at.ac.tuwien.sbc.valesriegler.pizzeria.gui.tablemodels;

import at.ac.tuwien.sbc.valesriegler.common.TableModel;
import at.ac.tuwien.sbc.valesriegler.common.Util;
import at.ac.tuwien.sbc.valesriegler.types.GroupData;
import at.ac.tuwien.sbc.valesriegler.types.Table;

import java.util.ArrayList;
import java.util.List;

public class TablesOverviewModel extends TableModel<Table> {
	private static final String TABLE_ID = "ID";
	private static final String STATUS = "Is free";
	private static final String GROUP_ID = "Group ID";
	private static final String[] COLUMNS = new String[] { TABLE_ID, STATUS, GROUP_ID };

	@Override
	protected String[] getColumns() {
		return COLUMNS;
	}

	@Override
	public Object getValueAt(int rowIndex, int columnIndex) {
		List<Table> values = new ArrayList<Table>(items.values());
		Table table = values.get(rowIndex);
		String wantedColumn = COLUMNS[columnIndex];
		switch (wantedColumn) {
		case TABLE_ID:
			return table.getId();
		case STATUS:
			return table.isFree();
		case GROUP_ID:
			return Util.getId(table.getGroupId());
		default:
			throw new RuntimeException(UNHANDLEDCOLUMN);
		}
	}

	public int getNumberOfFreeTables() {
		return getIdsOfFreeTables().size();
	}

	public List<Integer> getIdsOfFreeTables() {
		List<Integer> ids = new ArrayList<Integer>();

		synchronized (items) {
			for (Table table : items.values()) {
				if (table.isFree()) {
					ids.add(table.getId());
				}
			}
		}

		return ids;
	}

	public List<Table> createFreeTables(int numberOfTables) {
		List<Table> tables = new ArrayList<Table>();
		for (int i = 0; i < numberOfTables; i++) {
			Table table = createFreeTable();
			tables.add(table);
		}

		if (Util.useJMS)
			setItems(tables);

		return tables;
	}

	private Table createFreeTable() {
		return new Table();
	}

	public int getTableIdOfGroup(GroupData group) {
		synchronized (items) {
			for (Table table : items.values()) {
				if (table.getGroupId() == group.getId()) {
					return table.getId();
				}
			}
		}
		throw new RuntimeException("Could not find table with the wanted group");
	}

	public Table getTableById(int tableId) {
		synchronized (items) {
			for (Table table : items.values()) {
				if (table.getId() == tableId) {
					return table;
				}
			}
		}
		throw new RuntimeException("Could not find table with the wanted group");
	}
}
