
#include <string>
#include <stdarg.h>
#include <Spectre/System/Log.h>
#include <Spectre/System/Log/Writer.h>

namespace sp
{

log::Writer* Log::_writer;

void Log::setWriter(log::Writer* writer)
{
	_writer = writer;
}

void Log::info(const char *format, ...) {

	va_list vl;

	va_start(vl, format);
	writeln(T_INFO, format, vl);
	va_end(vl);
}

void Log::warn(const char *format, ...)
{
	va_list vl;

	va_start(vl, format);
	writeln(T_WARNING, format, vl);
	va_end(vl);
}

int Log::error(const char *format, ...)
{
	va_list vl;

	va_start(vl, format);
	writeln(T_ERROR, format, vl);
	va_end(vl);

	return 1;
}

void Log::debug(const char *format, ...)
{
#ifdef SPECTRE_DEBUG
	va_list vl;

	va_start(vl, format);
	writeln(T_DEBUG, format, vl);
	va_end(vl);
#endif /* SPECTRE_DEBUG */
}

void Log::writeln(Type type, const char *format, va_list args)
{
	int len;
	static char msg[4096];
	static char buf[4096];
	const char *prefix;

	switch(type) {
	case T_INFO :
		prefix = "INFO";
		break;
	case T_WARNING :
		prefix = "WARN";
		break;
	case T_CRITICAL:
		prefix = "CRIT";
		break;
#ifdef SPECTRE_DEBUG
	case T_DEBUG:
		prefix = "DEBUG";
		break;
#endif /* SPECTRE_DEBUG */
	case T_ERROR : 	default :
		prefix = "ERROR";
		break;
	}

	vsnprintf(msg, sizeof(msg), format, args);
	len = sprintf(buf, "%s: %s\n", prefix, msg);

	_writer->write(buf, len);
}

} // namespace sp
