package oving5.stringgrid;

import java.util.ArrayList;
import java.util.Collections;

public class StringGridImpl implements StringGrid {
	private ArrayList<String> grid;
	private int rows;
	private int columns;

	StringGridImpl(int rows, int columns) {
		grid = new ArrayList<String>(Collections.nCopies(rows * columns, ""));
		this.rows = rows;
		this.columns = columns;
	}

	public int getRowCount() {
		return rows;
	}

	public int getColumnCount() {
		return columns;
	}

	public String getElement(int row, int column) {
		if (row < 0 || row >= rows || column < 0 || column >= columns) {
			throw new IllegalArgumentException(
					"Invalid value for row or column, got row: " + row + ", and column: " + column);
		}
		return grid.get(row * columns + column);
	}

	public void setElement(int row, int column, String element) {
		if (row < 0 || row >= rows || column < 0 || column >= columns) {
			throw new IllegalArgumentException(
					"Invalid value for row or column, got row: " + row + ", and column: " + column);
		}
		grid.set(row * columns + column, element);
	}

	@Override
	public String toString() {
		String r = "";
		for (int y = 0; y < rows; y++) {
			for (int x = 0; x < columns; x++) {
				r += grid.get(y * columns + x);
				if (x < columns - 1) {
					r += " | ";
				}
			}
			r += "\n";
		}
		return r;
	}
}
