package function.builtin.cons;

import java.math.BigInteger;

import function.*;
import sexpression.*;

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

    public static BigInteger getLength(Cons list) {
        LENGTH lengthFunction = new LENGTH();
        LispNumber length = lengthFunction.callWithoutArgumentValidation(LIST.makeList(list));

        return length.getValue();
    }

    private ArgumentValidator argumentValidator;

    public LENGTH() {
        this.argumentValidator = new ArgumentValidator("LENGTH");
        this.argumentValidator.setExactNumberOfArguments(1);
        this.argumentValidator.setEveryArgumentExpectedType(Cons.class);
    }

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

        return callTailRecursive(BigInteger.ZERO, argumentList);
    }

    private LispNumber callWithoutArgumentValidation(Cons argumentList) {
        return callTailRecursive(BigInteger.ZERO, argumentList);
    }

    private LispNumber callTailRecursive(BigInteger accumulatedLength, Cons argumentList) {
        Cons list = (Cons) argumentList.getFirst();
        Cons restOfList = LIST.makeList(list.getRest());

        if (list.isNull())
            return new LispNumber(accumulatedLength);

        return callTailRecursive(increment(accumulatedLength), restOfList);
    }

    private BigInteger increment(BigInteger number) {
        return number.add(BigInteger.ONE);
    }

}
