/*
 * $Id$
 *
 * Code (c)2006 Bruno Cornec <bruno@mondorescue.org>
 *
 *     Main file of mr_msg : a very small and simple
 *     library for messages management
 *
 * Provided under the GPLv2
 */

#ifndef _GNU_SOURCE
#define _GNU_SOURCE
#endif
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>

static int mr_loglevel = 0;
static char *mr_logfile = NULL;

/*
 * This function is in the lowest part of the tree
 * It should not depend on any other function of the mr lib 
 */

/* Cleanup function for messages */
void mr_msg_close(void) {
	free(mr_logfile);
	mr_logfile = NULL;
	mr_loglevel = 0;
}

/* Initialization function for messages */
void mr_msg_init(const char *configfile, int loglevel) {
	FILE *fout = NULL;
	int res = 0;

	asprintf(&mr_logfile,configfile);
	if ((fout = fopen(mr_logfile, "w")) == NULL) {
		fprintf(stderr,"Unable to write to %s\n",mr_logfile);
		fprintf(stderr,"Logging desactivated\n");
		mr_msg_close();
	}
	if ((res = fclose(fout)) != 0) {
		fprintf(stderr,"Unable to close %s\n",mr_logfile);
	}
	mr_loglevel = loglevel;
}

/*
 * Function that log a message. Not called directly 
 * but through other functions
 * fmt needs to be just before ...
 */
void mr_msg_int(int debug, int line, const char *file, const char *fmt, ...) {

	int i = 0;
	int res = 0;
	FILE *fout = NULL;
	va_list args;

	if (mr_logfile == NULL) {
		return;
	}

	if (debug <= mr_loglevel) {
		if ((fout = fopen(mr_logfile, "a")) == NULL) {
			fprintf(stderr,"Unable to append to %s\n",mr_logfile);
			return;
		}

		// add 2 spaces to distinguish log levels
		if (debug > 0) {
			for (i = 1; i < debug; i++)
				fprintf(fout, "  ");
			fprintf(fout, "%s #%d: ", file, line);
		}
		va_start(args,fmt);
		if (vfprintf(fout, fmt, args) < 0) {
			fprintf(stderr,"Unable to print to %s\n",mr_logfile);
		}
		va_end(args);

		if ((res = fclose(fout)) != 0) {
			fprintf(stderr,"Unable to close %s\n",mr_logfile);
		}
	}
}
