package function.builtin.special;

import static function.builtin.EVAL.eval;

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

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

    private ArgumentValidator argumentValidator;

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

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

        return callTailRecursive(argumentList);
    }

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

        if (remainingValues.isNull() || !currentValue.isNull())
            return currentValue;

        return callTailRecursive(remainingValues);
    }

}
