package function.builtin.math;

import error.LispException;
import function.ArgumentValidator;
import function.FunctionNames;
import function.LispFunction;
import sexpression.Cons;
import sexpression.LispNumber;
import sexpression.SExpression;

@FunctionNames({ "MOD", "MODULO", "%" })
public class MODULO extends LispFunction {

    private ArgumentValidator argumentValidator;

    public MODULO(String name) {
        this.argumentValidator = new ArgumentValidator(name);
        this.argumentValidator.setExactNumberOfArguments(2);
        this.argumentValidator.setEveryArgumentExpectedType(LispNumber.class);
    }

    @Override
    public SExpression call(Cons argumentList) {
        argumentValidator.validate(argumentList);
        LispNumber dividend = (LispNumber) argumentList.getFirst();
        LispNumber divisor = (LispNumber) ((Cons) argumentList.getRest()).getFirst();

        try {
            return new LispNumber(dividend.getValue().mod(divisor.getValue()));
        } catch (ArithmeticException e) {
            throw new ModulusNotPositiveException();
        }
    }

    public static class ModulusNotPositiveException extends LispException {

        private static final long serialVersionUID = 1L;

        @Override
        public String getMessage() {
            return "modulus not positive";
        }
    }

}
