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({ "EQ", "EQ?" })
public class EQ extends LispFunction {

    private ArgumentValidator argumentValidator;

    public EQ(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 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 isEq(firstArgument, secondArgument) ? T : NIL;
    }

    private boolean isEq(SExpression firstArgument, SExpression secondArgument) {
        return firstArgument.toString().equals(secondArgument.toString());
    }

    private SExpression listEq(SExpression firstArgument, SExpression secondArgument) {
        return (firstArgument == secondArgument) ? T : NIL;
    }

}
