package function.builtin.special;

import static function.builtin.EVAL.eval;
import static sexpression.Nil.NIL;

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

@FunctionNames({ "PROGN", "BEGIN" })
public class PROGN extends LispSpecialFunction {

    private ArgumentValidator argumentValidator;

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

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

        return callTailRecursive(argumentList, NIL);
    }

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

        if (argumentList.isNull())
            return lastValue;

        return callTailRecursive(remainingValues, currentValue);
    }

}
