package expression;

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

/**
 * @author Doschennikov Nikita (me@fymio.us)
 */
public class Reverse extends AbstractExpression {

    private final AbstractExpression operand;

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

    private static int reverseInt(int n) {
        boolean negative = n < 0;
        long abs = Math.abs((long) n);
        long reversed = 0;
        while (abs > 0) {
            reversed = reversed * 10 + (abs % 10);
            abs /= 10;
        }
        long result = negative ? -reversed : reversed;
        return (int) result;
    }

    @Override
    public int evaluate(int x) {
        return reverseInt(operand.evaluate(x));
    }

    @Override
    public int evaluate(int x, int y, int z) {
        return reverseInt(operand.evaluate(x, y, z));
    }

    @Override
    public int evaluate(List<Integer> vars) {
        return reverseInt(operand.evaluate(vars));
    }

    @Override
    public BigInteger evaluateBi(List<BigInteger> vars) {
        throw new UnsupportedOperationException(
            "reverse not supported for BigInteger"
        );
    }

    @Override
    public BigDecimal evaluateBd(List<BigDecimal> vars) {
        throw new UnsupportedOperationException(
            "reverse not supported for BigDecimal"
        );
    }

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

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

        return "reverse " + operand.toMiniString();
    }

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

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