package migl.lisp.operator;

import migl.lisp.LispElement;
import migl.lisp.LispError;
import migl.lisp.LispOperator;
import migl.util.ConsList;

public class ComparatorOperator implements LispOperator {

	@Override
	public LispElement apply(String operator, ConsList<Object> lisp) throws LispError {
		if(lisp.size() == 0) {
			throw new LispError(LispError.ERR_NUM_ARG);
		}
		boolean result = true;
		boolean first = true;
		double value = 0;
		while(!lisp.isEmpty()) {
			if(first) {
				value = LispElement.getElement(lisp.car()).toNumber();
				first = false;
			} else {
				double temp = LispElement.getElement(lisp.car()).toNumber();
				switch(operator) {
					case ">":
						result = result && (value > temp);
						break;
					case ">=":
						result = result && (value >= temp);
						break;
					case "<":
						result = result && (value < temp);
						break;
					case "<=":
						result = result && (value <= temp);
						break;
					case "=":
						result = result && (value == temp);
						break;
					default:
						throw new LispError("Unknow operation");
				}
				value = temp;
			}
			lisp = lisp.cdr();
		}
		return LispElement.generate(result);
	}

}
