package function.builtin;

import function.*;
import sexpression.*;

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

    private ArgumentValidator argumentValidator;

    public static SExpression apply(Cons argumentList) {
        return new APPLY().call(argumentList);
    }

    public APPLY() {
        this.argumentValidator = new ArgumentValidator("APPLY");
        this.argumentValidator.setExactNumberOfArguments(2);
        this.argumentValidator.setTrailingArgumentExpectedType(Cons.class);
    }

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

        Cons rest = (Cons) argumentList.getRest();
        SExpression functionName = argumentList.getFirst();
        SExpression functionArguments = rest.getFirst();
        LispFunction function = EVAL.lookupFunctionOrLambda(functionName);

        return function.call((Cons) functionArguments);
    }

}
