package org.xbib.logging.ext.util.formatter;

public final class ColorUtil {

    private ColorUtil() {
    }

    public static StringBuilder startFgColor(StringBuilder target, boolean trueColor, int r, int g, int b) {
        return startColor(target, 38, trueColor, r, g, b);
    }

    public static StringBuilder startBgColor(StringBuilder target, boolean trueColor, int r, int g, int b) {
        return startColor(target, 48, trueColor, r, g, b);
    }

    public static StringBuilder startColor(StringBuilder target, int mode, boolean trueColor, int r, int g, int b) {
        if (trueColor) {
            return target.appendCodePoint(27).append('[').append(mode).append(';').append(2).append(';').append(clip(r))
                    .append(';').append(clip(g)).append(';').append(clip(b)).append('m');
        } else {
            int ar = (5 * clip(r)) / 255;
            int ag = (5 * clip(g)) / 255;
            int ab = (5 * clip(b)) / 255;
            int col = 16 + 36 * ar + 6 * ag + ab;
            return target.appendCodePoint(27).append('[').append(mode).append(';').append('5').append(';').append(col)
                    .append('m');
        }
    }

    private static int clip(int color) {
        return Math.min(Math.max(0, color), 255);
    }

    public static StringBuilder endFgColor(StringBuilder target) {
        return endColor(target, 39);
    }

    public static StringBuilder endBgColor(StringBuilder target) {
        return endColor(target, 49);
    }

    public static StringBuilder endColor(StringBuilder target, int mode) {
        return target.appendCodePoint(27).append('[').append(mode).append('m');
    }
}
