#pragma GCC diagnostic error "-Wall"
#pragma GCC diagnostic error "-Wextra"
#if defined(HARDWARE_BT6711) && !defined(BT6702_SERVICE)
#include "common_config.h"
#include "syslog.h"
#include "settings_api.h"
#include "tcpip.h"
#include "udp.h"
#include "rtc.h"
#include "netconf.h"
#include <assert.h>

static struct udp_pcb *upcb;

// TODO either lock the buffers against race conditions or raise the task stack sizes, or lower the memory consumption
static char packet[256];
static char msg[200];

void openlog(void)
{
	upcb = udp_new();
	udp_bind(upcb, IP_ADDR_ANY, 0);
}

static void timestamp_rfc3339(char *ts)
{
	TM_RTC_t data;
	uint16_t sys_year;

	TM_RTC_GetDateTime(&data, TM_RTC_Format_BIN);
	sys_year = 2000 + data.year;
	uint32_t subseconds = (1024 - data.subseconds) * 999999 / 1024;
	// TODO timezone?
	sprintf(ts, "%04i-%02i-%02iT%02i:%02i:%02i.%06luZ", sys_year, data.month, data.date, data.hours, data.minutes, data.seconds, subseconds);
}

void syslog(uint8_t severity, char *fmt, ...)
{
	//char msg[200]; // arbitrary length; "Any transport receiver MUST be able to accept messages of up to and including 480 octets in length."
	va_list va;
	va_start(va, fmt);
	vsnprintf(msg, sizeof(msg), fmt, va);
	syslog_str(severity, msg);
	va_end(va);
}

void syslog_str(uint8_t severity, char *msg)
{
	const uint8_t facility = 1;
	assert(severity < 8);
	uint8_t priority = facility * 8 + severity;
#define SYSLOG_VERSION "1" // as defined in RFC5424
#define BOM "\xef\xbb\xbf"
	struct pbuf* psend;
	// TODO to reduce memory consumption one can use a scatter-gather I/O instead of packet[]
	//char packet[256]; // arbitrary length; "Any transport receiver MUST be able to accept messages of up to and including 480 octets in length."
	static char timestamp[30];
	timestamp_rfc3339(timestamp);
	unsigned len = snprintf(packet, sizeof(packet), "<%u>" SYSLOG_VERSION " %s %s " HW_REV "_" VERSION " - - - " BOM "%s", priority, timestamp, ipaddr_ntoa(&xnetif.ip_addr), msg);
	//psend = pbuf_alloc(PBUF_RAW, sizeof(packet), PBUF_REF);
	psend = pbuf_alloc(PBUF_RAW, len, PBUF_REF);
	psend->payload = packet;
	//psend->len = len;
	udp_sendto(upcb, psend, &sSettings.sSyslog.server_ip, sSettings.sSyslog.server_port);
	pbuf_free(psend);
}
#endif // defined(HARDWARE_BT6711) && !defined(BT6702_SERVICE)
