/*
 * @(#)Log.cpp
 *
 * This file is part of webCDwriter - Network CD Writing.
 *
 * Copyright (C) 1999-2002 Jörg P. M. Haeger
 *
 * webCDwriter is free software. See CDWserver.cpp for details.
 */

#include <stdarg.h>
#include <stdio.h>
#include <sys/time.h>
#include <unistd.h>
#include "Config.h"
#include "Log.h"

Log::Log() {
	pthread_mutex_init(&mutex, NULL);
	counter = 0;
	lastLine[0] = 0;
	outStream = NULL;
}

void Log::debug(const char *tag, const char *format, ...) {
	if (config.getLogLevel() == 9
		|| strstr(config.getDebug(), tag) != NULL) {
		char str[sizeof lastLine];
		va_list ap;
		va_start(ap, format);
		vsnprintf(str, sizeof str, format, ap);
		va_end(ap);
		put(9, "%s %s", tag, str);
	}
}

void Log::put(int level, const char *format, ...) {
	if (level > config.getLogLevel())
		return;

	char str[sizeof lastLine];
	va_list ap;
	va_start(ap, format);
	vsnprintf(str, sizeof str, format, ap);
	va_end(ap);
	writeLine(level, str);
}

void Log::put(const char *format, ...) {
	char line[sizeof lastLine];
	va_list ap;
	va_start(ap, format);
	vsnprintf(line, sizeof line, format, ap);
	va_end(ap);

	writeLine(3, line);
}

void Log::putv(const char *format, ...) {
	char line[sizeof lastLine];
	va_list ap;
	va_start(ap, format);
	vsnprintf(line, sizeof line, format, ap);
	va_end(ap);

	writeLine(4, line);
}

void Log::start(int toStdOut) {
	if (toStdOut)
		outStream = stdout;
	else {
		File logFile = new File(config.getLogDir(), "log");
		outStream = fopen(logFile.getPath().getBytes(), "a");
	}
}

void Log::writeLine(int level, char *line) {
	if (outStream == NULL)
		return;

	for (int i = 0; line[i] != 0; i++)
		if (line[i] == '\n')
			line[i] = '\\';

	pthread_mutex_lock(&mutex);
	if (strcmp(line, lastLine) == 0)
		counter++;
	else {
		time_t t;
		time(&t);
		struct tm *tm = localtime(&t);
		fprintf(outStream, "%02d%02d%02d T%05d L%d",
			tm->tm_hour, tm->tm_min, tm->tm_sec,
			getpid(), level);
		if (counter > 0) {
			fprintf(outStream, " repeated %d times\n", counter);
			counter = 0;
		}
		else
			fprintf(outStream, " %s\n", line);
	}
	strcpy(lastLine, line);
	pthread_mutex_unlock(&mutex);

	fflush(outStream);
}
