package function.builtin.predicate;

import function.*;
import sexpression.*;

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

    private ArgumentValidator argumentValidator;

    public EQ() {
        this.argumentValidator = new ArgumentValidator("EQ");
        this.argumentValidator.setExactNumberOfArguments(2);
    }

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

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

        return eq(firstArgument, secondArgument);
    }

    private SExpression eq(SExpression firstArgument, SExpression secondArgument) {
        if (isAtomPair(firstArgument, secondArgument))
            return atomEq(firstArgument, secondArgument);

        return listEq(firstArgument, secondArgument);
    }

    private boolean isAtomPair(SExpression firstArgument, SExpression secondArgument) {
        return firstArgument.isAtom() && secondArgument.isAtom();
    }

    private SExpression atomEq(SExpression firstArgument, SExpression secondArgument) {
        return (firstArgument.toString().equals(secondArgument.toString())) ? Symbol.T : Nil.getInstance();
    }

    private SExpression listEq(SExpression firstArgument, SExpression secondArgument) {
        return (firstArgument == secondArgument) ? Symbol.T : Nil.getInstance();
    }

}
