Grid.java 2.09 KB
package kernel;

import kernel.exception.CellNotFoundException;

import java.util.HashMap;
import java.util.Map;

public class Grid {

    private Map<String, Cell> cells = new HashMap<>();

    public String createCell(String column, Integer line, Double value) {
        String id = this.getId(column, line);
        Cell cell = new Cell(column, line, value);

        this.cells.put(id, cell);

        return id;
    }

    public String createCell(String column, Integer line, Formula formula) {
        String id = this.getId(column, line);
        Cell cell = new Cell(column, line, formula);

        this.cells.put(id, cell);

        return id;
    }

    public void setValue(String column, Integer line, Double value) throws CellNotFoundException {
        Cell cell = this.getCell(column, line);

        try {
            cell.setValue(value);
        } catch (NullPointerException exception) {
            throw new CellNotFoundException();
        }
    }

    public void setFormula(String column, Integer line, Formula formula) throws CellNotFoundException {
        Cell cell = this.getCell(column, line);

        try {
            cell.setFormula(formula);
        } catch (NullPointerException exception) {
            throw new CellNotFoundException();
        }
    }

    public Cell getCell(String column, Integer line) {
        return this.cells.get(this.getId(column, line));
    }

    public Double getValue(String column, Integer line) throws CellNotFoundException {
        Cell cell = this.getCell(column, line);

        try {
            return cell.getValue();
        } catch (NullPointerException exception) {
            throw new CellNotFoundException();
        }
    }

    public String getFormulaAsString(String column, Integer line) throws CellNotFoundException {
        Cell cell = this.getCell(column, line);

        try {
            return cell.getFormula().toString();
        } catch (NullPointerException exception) {
            throw new CellNotFoundException();
        }
    }

    private String getId(String column, Integer line) {
        return column + line.toString();
    }
}