Cell.java 2.64 KB
package kernel;

import kernel.exception.CreateCycleException;
import kernel.exception.InvalidIntervalLineColumnEception;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

public class Cell implements Serializable{
	final int MAX_LIGNES=20;
	
    private String column;
    private Integer line;
    private Double value;
    private Formula formula;
    private List<Cell> usedIn = new ArrayList<>();

    public Cell(String column, Integer line, Double value) throws InvalidIntervalLineColumnEception {
    	column=column.toUpperCase();
    	if ((line>= 1 && line<=MAX_LIGNES) || (column.compareTo("A")>=0 && column.compareTo("Z")<=0)){
    		 this.column = column;
    	     this.line = line;
    	     this.setValue(value);
    	}
    	else
    		throw new InvalidIntervalLineColumnEception();
    }

    public Cell(String column, Integer line, Formula formula) throws CreateCycleException,InvalidIntervalLineColumnEception {
    	column=column.toUpperCase();
    	if ((line>= 1 && line<=MAX_LIGNES) || (column.compareTo("A")>=0 && column.compareTo("Z")<=0)){
    		 this.column = column;
    	     this.line = line;
    	     this.setFormula(formula);
    	}
    	else
    		throw new InvalidIntervalLineColumnEception();
        
    }

    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.toString();
    }

    public List<Cell> 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 Boolean containFormula() {
        return this.formula != null;
    }

    public void setFormula(Formula formula) throws CreateCycleException {
        if (formula.createCycle(this))
            throw new CreateCycleException();
        else {
            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();
        }
    }
}