package expression;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.List;

/**
 * @author Doschennikov Nikita (me@fymio.us)
 */
public class Cbrt extends AbstractExpression {
    private final AbstractExpression operand;

    public Cbrt(AbstractExpression operand) {
        this.operand = operand;
    }

    private static int cbrtInt(int n) {
        if (n == 0) return 0;
        boolean negative = n < 0;
        int abs = (n == Integer.MIN_VALUE) ? Integer.MAX_VALUE : (negative ? -n : n);

        int lo = 0, hi = 1290;
        while (lo < hi) {
            int mid = (lo + hi + 1) / 2;
            if (mid * mid * mid <= abs) {
                lo = mid;
            } else {
                hi = mid - 1;
            }
        }
        return negative ? -lo : lo;
    }

    @Override public int        evaluate(int x)               { return cbrtInt(operand.evaluate(x)); }
    @Override public int        evaluate(int x, int y, int z) { return cbrtInt(operand.evaluate(x,y,z)); }
    @Override public int        evaluate(List<Integer> vars)  { return cbrtInt(operand.evaluate(vars)); }
    @Override public BigInteger evaluateBi(List<BigInteger> vars) {
        throw new UnsupportedOperationException("∛ not supported for BigInteger");
    }
    @Override public BigDecimal evaluateBd(List<BigDecimal> vars) {
        throw new UnsupportedOperationException("∛ not supported for BigDecimal");
    }

    @Override public String toString()     { return "∛(" + operand + ")"; }

    @Override
    public String toMiniString() {
        if (operand instanceof AbstractBinaryOperation) {
            return "∛(" + operand.toMiniString() + ")";
        }
        return "∛" + operand.toMiniString();
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if (!(obj instanceof Cbrt)) return false;
        return operand.equals(((Cbrt) obj).operand);
    }

    @Override public int hashCode() { return operand.hashCode() ^ 0x43425254; }
}