package function.builtin.special;

import static function.builtin.EVAL.eval;
import static sexpression.Symbol.T;

import function.ArgumentValidator;
import function.FunctionNames;
import function.LispSpecialFunction;
import sexpression.Cons;
import sexpression.SExpression;

@FunctionNames({ "AND" })
public class AND extends LispSpecialFunction {

    private ArgumentValidator argumentValidator;

    public AND(String name) {
        this.argumentValidator = new ArgumentValidator(name);
    }

    @Override
    public SExpression call(Cons argumentList) {
        argumentValidator.validate(argumentList);

        return callTailRecursive(argumentList, T);
    }

    private SExpression callTailRecursive(Cons argumentList, SExpression lastValue) {
        SExpression currentValue = eval(argumentList.getFirst());
        Cons remainingValues = (Cons) argumentList.getRest();

        if (argumentList.isNull())
            return lastValue;

        if (currentValue.isNull())
            return currentValue;

        return callTailRecursive(remainingValues, currentValue);
    }

}
