/*
 * Copyright (c) 2016-2021 Satlab A/S <satlab@satlab.com>
 * All rights reserved. Do not distribute without permission.
 */

#include <util/colorprint.h>

#include <stdio.h>
#include <stdarg.h>

int color_set(char *buf, sl_color_t color)
{
	unsigned int color_code, modifier_code;

	switch (color & COLOR_MASK_COLOR) {
	case COLOR_BLACK:
		color_code = 30; break;
	case COLOR_RED:
		color_code = 31; break;
	case COLOR_GREEN:
		color_code = 32; break;
	case COLOR_YELLOW:
		color_code = 33; break;
	case COLOR_BLUE:
		color_code = 34; break;
	case COLOR_MAGENTA:
		color_code = 35; break;
	case COLOR_CYAN:
		color_code = 36; break;
	case COLOR_LIGHT_GRAY:
		color_code = 37; break;
	case COLOR_DARK_GRAY:
		color_code = 90; break;
	case COLOR_LIGHT_RED:
		color_code = 91; break;
	case COLOR_LIGHT_GREEN:
		color_code = 92; break;
	case COLOR_LIGHT_YELLOW:
		color_code = 93; break;
	case COLOR_LIGHT_BLUE:
		color_code = 94; break;
	case COLOR_LIGHT_MAGENTA:
		color_code = 95; break;
	case COLOR_LIGHT_CYAN:
		color_code = 96; break;
	case COLOR_WHITE:
		color_code = 97; break;
	default:
		color_code = 39; break;
	}

	switch (color & COLOR_MASK_MODIFIER) {
	case COLOR_BOLD:
	case COLOR_BRIGHT:
		modifier_code = 1; break;
	case COLOR_DIM:
		modifier_code = 2; break;
	case COLOR_UNDERLINE:
		modifier_code = 4; break;
	case COLOR_BLINK:
		modifier_code = 5; break;
	case COLOR_REVERSE:
		modifier_code = 7; break;
	case COLOR_HIDDEN:
		modifier_code = 8; break;
	default:
		modifier_code = 0; break;
	}

	return sprintf(buf, "\033[%u;%um", modifier_code, color_code);
}

int cprintf(sl_color_t color, const char *format, ...)
{
	int ret;
	va_list args;
	char colorbuf[10];

	va_start(args, format);

	color_set(colorbuf, color);
	printf("%s", colorbuf);

	ret = vprintf(format, args);

	color_set(colorbuf, COLOR_RESET);
	printf("%s", colorbuf);

	va_end(args);

	return ret;
}
