package expression.exceptions;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.math.MathContext;

import expression.*;

/**
 * @author Doschennikov Nikita (me@fymio.us)
 */
public class CheckedDivide extends AbstractBinaryOperation {
    public CheckedDivide(AbstractExpression l, AbstractExpression r) { super(l, r); }

    @Override protected String  getOperator()  { return "/"; }
    @Override protected int     getPriority()  { return 2; }
    @Override protected boolean isRightAssoc() { return true; }

    @Override
    protected int applyInt(int a, int b) {
        if (b == 0) throw new DivisionByZeroException();
        if (a == Integer.MIN_VALUE && b == -1) throw new OverflowException("division");
        return a / b;
    }

    @Override
    protected BigInteger applyBi(BigInteger a, BigInteger b) {
        if (b.signum() == 0) throw new DivisionByZeroException();
        return a.divide(b);
    }

    @Override
    protected BigDecimal applyBd(BigDecimal a, BigDecimal b) {
        if (b.signum() == 0) throw new DivisionByZeroException();
        return a.divide(b, MathContext.DECIMAL128);
    }
}