package function.builtin.math;

import function.ArgumentValidator;
import function.FunctionNames;
import function.LispFunction;
import function.builtin.math.DIVIDE.DivideByZeroException;
import sexpression.Cons;
import sexpression.LispNumber;
import sexpression.SExpression;

@FunctionNames({ "REM", "REMAINDER" })
public class REMAINDER extends LispFunction {

    private ArgumentValidator argumentValidator;

    public REMAINDER(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().remainder(divisor.getValue()));
        } catch (ArithmeticException e) {
            throw new DivideByZeroException();
        }
    }

}
