package ctbrec;

import java.text.DecimalFormat;

public class StringUtil {
    private StringUtil() {}

    public static boolean isBlank(String s) {
        return s == null || s.trim().isEmpty();
    }

    public static boolean isNotBlank(String s) {
        return !isBlank(s);
    }

    public static String formatSize(Number sizeInByte) {
        if (sizeInByte.longValue() < 0) {
            return "n/a";
        }

        DecimalFormat df = new DecimalFormat("0.00");
        String unit = "Bytes";
        double size = sizeInByte.doubleValue();
        if (size > 1024.0 * 1024 * 1024) {
            size = size / 1024.0 / 1024 / 1024;
            unit = "GiB";
        } else if (size > 1024.0 * 1024) {
            size = size / 1024.0 / 1024;
            unit = "MiB";
        } else if (size > 1024.0) {
            size = size / 1024.0;
            unit = "KiB";
        }
        return df.format(size) + ' ' + unit;
    }

    public static String toHexString(byte[] bytes, int bytesPerRow) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i += bytesPerRow) {
            int length = bytes.length - i >= bytesPerRow ? bytesPerRow : bytes.length % bytesPerRow;
            byte[] row = new byte[bytesPerRow];
            System.arraycopy(bytes, i, row, 0, length);
            for (int j = 0; j < length; j++) {
                sb.append(toHexString(row[j]));
            }
        }
        return sb.toString();
    }

    /**
     * Converts one byte to its hex representation with leading zeros. E.g. 255 -> FF, 12 -> 0C
     *
     * @param b
     * @return
     */
    public static String toHexString(int b) {
        String hex = Integer.toHexString(b & 0xFF);
        if (hex.length() < 2) {
            hex = "0" + hex;
        }
        return hex;
    }
}
