package expression;

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

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

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

    private static int highestBit(int n) {
        if (n == 0) return 0;
        n |= (n >> 1);
        n |= (n >> 2);
        n |= (n >> 4);
        n |= (n >> 8);
        n |= (n >> 16);
        return n - (n >>> 1);
    }

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

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

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

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

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