package kernel; import kernel.exception.CreateCycleException; import java.io.Serializable; import java.util.ArrayList; import java.util.List; import java.util.Objects; public class Cell implements Serializable { private static final long serialVersionUID = 1L; private String column; private int line; private double value; private Formula formula; private List usedIn = new ArrayList<>(); public Cell(String column, int line, double value) { this.column = column; this.line = line; this.setValue(value); } public Cell(String column, int line, Formula formula) throws CreateCycleException { this.column = column; this.line = line; this.setFormula(formula); } public double getValue() { return this.value; } public Formula getFormula() { return this.formula; } public String getDevelopedFormula() { return this.containFormula() ? this.formula.getDevelopedFormula() : this.getId(); } public String getId() { return this.column + this.line; } public List getUsedIn() { return this.usedIn; } public String toString() { return this.containFormula() ? this.formula.toString() : this.getId(); } public void updateValue() { if (this.containFormula()) this.value = this.formula.eval(); } public void updateUsedIn() { if (this.containFormula()) { for (Cell cell : this.formula.getUtilisedCells()) cell.getUsedIn().remove(this); } } public boolean containFormula() { return this.formula != null; } public void setFormula(Formula formula) throws CreateCycleException { if (formula.createCycle(this)) throw new CreateCycleException("L'assignation de la formule " + formula.toString() + " créée un cycle."); this.formula = formula; for (Cell cell : this.formula.getUtilisedCells()) cell.usedIn.add(this); this.updateValue(); this.spreadValue(); } public void setValue(double value) { this.value = value; this.formula = null; this.spreadValue(); } private void spreadValue() { for (Cell cell : this.usedIn) { cell.updateValue(); cell.spreadValue(); } } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof Cell)) return false; Cell cell = (Cell) o; return line == cell.line && column.equals(cell.column); } @Override public int hashCode() { return Objects.hash(column, line); } }