package function.builtin.special;

import static function.builtin.EVAL.eval;
import static function.builtin.SET.set;
import static function.builtin.cons.LIST.makeList;

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

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

    private ArgumentValidator argumentValidator;

    public SETQ(String name) {
        this.argumentValidator = new ArgumentValidator(name);
        this.argumentValidator.setExactNumberOfArguments(2);
        this.argumentValidator.setFirstArgumentExpectedType(Symbol.class);
    }

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

        return set(evaluateValueOnly(argumentList));
    }

    private Cons evaluateValueOnly(Cons argumentList) {
        Cons rest = (Cons) argumentList.getRest();
        SExpression value = eval(rest.getFirst());

        return new Cons(argumentList.getFirst(), makeList(value));
    }

}
