/*
 * log.c - XMPP log functions
 *
 * Copyright (C) 2022, IOPSYS Software Solutions AB.
 *
 * Author: Amin Ben Ramdhane <amin.benramdhane@pivasoftware.com>
 *
 * See LICENSE file for license related information.
 *
 */

#include <stdio.h>
#include <stdarg.h>
#include <time.h>
#include <syslog.h>
#include <strophe.h>

#include "log.h"
#include "xmpp.h"

static const int log_syslogmap[] = {
	[SCRIT] = LOG_CRIT,
	[SWARNING] = LOG_WARNING,
	[SNOTICE] = LOG_NOTICE,
	[SINFO] = LOG_INFO,
	[SDEBUG] = LOG_DEBUG
};

void xmpp_syslog(int priority, const char *format, ...)
{
	if (priority <= cur_xmpp_conf.xmpp_loglevel) {
		va_list vl;

		va_start(vl, format);
		vsyslog(log_syslogmap[priority], format, vl);
		va_end(vl);
	}
}

void xmpp_syslog_handler(void * const userdata,
			 const xmpp_log_level_t level,
			 const char * const area,
			 const char * const msg)
{
	xmpp_log_level_t filter_level = *(xmpp_log_level_t *)userdata;

	if (level >= filter_level) {
		int priority;

		switch (level) {
		case XMPP_LEVEL_ERROR:
			priority = SCRIT;
			break;
		case XMPP_LEVEL_WARN:
			priority = SWARNING;
			break;
		case XMPP_LEVEL_INFO:
			priority = SINFO;
			break;
		default:
			priority = SDEBUG;
			break;
		}

		xmpp_syslog(priority, "%s %s", area, msg);
	}
}

xmpp_log_level_t xmpp_log_get_level(int conf_loglevel)
{
	xmpp_log_level_t xmpp_level = XMPP_LEVEL_DEBUG;

	switch (conf_loglevel) {
	case SCRIT:
		xmpp_level = XMPP_LEVEL_ERROR;
		break;
	case SWARNING:
		xmpp_level = XMPP_LEVEL_WARN;
		break;
	case SINFO:
	case SNOTICE:
		xmpp_level = XMPP_LEVEL_INFO;
		break;
	case SDEBUG:
		xmpp_level = XMPP_LEVEL_DEBUG;
		break;
	}

	return xmpp_level;
}
