package function.builtin.special;

import static function.builtin.EVAL.eval;
import static recursion.TailCalls.done;
import static recursion.TailCalls.tailCall;
import static sexpression.Symbol.T;

import function.ArgumentValidator;
import function.FunctionNames;
import function.LispSpecialFunction;
import recursion.TailCall;
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).invoke();
    }

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

        if (argumentList.isNull())
            return done(lastValue);

        if (currentValue.isNull())
            return done(currentValue);

        return tailCall(() -> callTailRecursive(remainingValues, currentValue));
    }

}
