package de.planetmetax.spreadsheet.reader;

import java.util.ArrayList;

/**
 * This class provides access to the data of an ODT spreadsheet.
 * @author Christian Simon
 */
public class SpreadsheetData {

	/**
	 * Local matrix for table data
	 */
	private ArrayList<ArrayList<String>> _data;
	
	/**
	 * Construct empty spreadsheet data matrix
	 */
	public SpreadsheetData() {
		_data = new ArrayList<ArrayList<String>>();
	}
	
	/**
	 * Get the number of rows in the matrix.
	 * @return the number of rows
	 */
	public int rows() {
		return _data.size();
	}
	
	/**
	 * Get the number of columns in a specific row.
	 * The matrix will likely be rectangular, so columns() might be the same for every row.
	 * @param row the row. Starts with 0.
	 * @return number of columns
	 * @throws IndexOutOfBoundsException if the row is not a valid row number
	 */
	public int columns(int row) throws IndexOutOfBoundsException {
		return _data.get(row).size();
	}
	
	/**
	 * Get the value of a cell of the table.
	 * @param row the row number. Starts with 0.
	 * @param column the column number. Starts with 0.
	 * @return the value at the specific table cell
	 * @throws IndexOutOfBoundsException
	 */
	public String value(int row, int column) throws IndexOutOfBoundsException {
		return _data.get(row).get(column);
	}
	
	/**
	 * Insert a value into the data matrix.
	 * Since this class cannot modify an ODT Spreadsheet, this method should only be invoked by {@link SpreadsheetReader#openSpreadsheet(String, int)}
	 * and its private help methods.
	 * @param row the row. Starts with 0.
	 * @param column the column. Starts with 0.
	 * @param value the text value at the cell position
	 */
	protected void insert(int row, int column, String value) {
		while (row >= _data.size()) {
			_data.add(new ArrayList<String>());
		}
		while (column >= _data.get(row).size()) {
			_data.get(row).add(null);
		}
		_data.get(row).set(column, value);
	}
	
	@Override
	public String toString() {
		StringBuffer buffer = new StringBuffer();
		for (ArrayList<String> row : _data) {
			buffer.append("| ");
			for (String col : row) {
				buffer.append(col + "\t| ");
			}
			buffer.append("\n");
		}
		return buffer.toString();
	}
	
}

