package function.builtin.predicate;

import static sexpression.Nil.NIL;
import static sexpression.Symbol.T;

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

@FunctionNames({ "EQUAL", "EQUAL?" })
public class EQUAL extends LispFunction {

    public static boolean isEqual(SExpression firstArgument, SExpression secondArgument) {
        return firstArgument.toString().equals(secondArgument.toString());
    }

    private ArgumentValidator argumentValidator;

    public EQUAL(String name) {
        this.argumentValidator = new ArgumentValidator(name);
        this.argumentValidator.setExactNumberOfArguments(2);
    }

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

        Cons rest = (Cons) argumentList.getRest();
        SExpression firstArgument = argumentList.getFirst();
        SExpression secondArgument = rest.getFirst();

        return equal(firstArgument, secondArgument);
    }

    private SExpression equal(SExpression firstArgument, SExpression secondArgument) {
        return isEqual(firstArgument, secondArgument) ? T : NIL;
    }

}
