package function.builtin.cons;

import static sexpression.Nil.NIL;

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

@FunctionNames({ "LIST" })
public class LIST extends LispFunction {

    public static Cons makeList(SExpression sexpr) {
        return new Cons(sexpr, NIL);
    }

    private ArgumentValidator argumentValidator;

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

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

        return callRecursive(argumentList);
    }

    private Cons callRecursive(Cons argumentList) {
        if (argumentList.isNull())
            return NIL;

        SExpression firstArgument = argumentList.getFirst();
        Cons remainingArguments = (Cons) argumentList.getRest();

        return new Cons(firstArgument, callRecursive(remainingArguments));
    }

}
