package calc.cell;
import calc.Sheet;
import calc.CellId;
import calc.cell.Cell;
import java.lang.*;
import java.util.*;
import calc.CellId;
import calc.MalformedFormulaException;
import calc.eval.*;

final public class FormulaCell extends Cell implements Evaluatable {
	private List<CellId> ids;
	public FormulaCell(Sheet sheet) {
		super(sheet);
		ids = new ArrayList<>();
	}

	@Override
	public void edit(String newContent) throws MalformedFormulaException{
	if(!newContent.substring(0,1).equals("=")){throw new MalformedFormulaException("Formula must start with a = sign", newContent);}
	//System.out.println(newContent);
		String ss=newContent.substring(1);
		for(String s : ss.split("\\+")){
			try{
				CellId c=CellId.fromString(s);
				if(c==null){throw new MalformedFormulaException("Invalid cell reference", newContent);}
				ids.add(c);
			}catch(Exception ex){throw new MalformedFormulaException("Invalid cell reference", newContent);}
		}
	}

	@Override
	public Integer eval() {
		int sum=0;
		for(CellId c : ids){
			Cell ce = sheet.getCell(c);
			if(ce!=null)sum+=ce.eval();//3ICE: eval int-et ad vissza, míg a show String-et adna. Eval jobb itt.
		}
		return sum;
	}

	@Override
	public String show() {
		return eval().toString();
	}
}