#include "mda.h"

#ifdef WIN32
int logfacility;
char *logident;
struct sockaddr_in loghost;
SOCKET logsocket = INVALID_SOCKET;
char logsource[MAX_COMPUTERNAME_LENGTH + 1];

void openlogsocket ()
{
	if (logsocket != INVALID_SOCKET)
		return;

	logsocket = socket (PF_INET, SOCK_DGRAM, 0);

	if (logsocket == INVALID_SOCKET)	
		return;

	if (config.loghost == NULL) {
		loghost.sin_addr.s_addr = inet_addr ("127.0.0.1");
	} else {
		loghost.sin_addr.s_addr = inet_addr (config.loghost);

		if (INADDR_NONE == loghost.sin_addr.s_addr)
		{
			HOSTENT	*hostent;

			hostent = gethostbyname (config.loghost);
			
			if (!hostent) {
				closesocket (logsocket);
				logsocket = INVALID_SOCKET;
				return;
			}

			loghost.sin_addr.s_addr = *(uint32_t *)hostent->h_addr_list[0];
		}
	}

	loghost.sin_port = htons (514);
	loghost.sin_family = AF_INET;
}

void openlog (const char *ident, int option, int facility)
{
	WSADATA	wsaData;

	if (WSAStartup (MAKEWORD (2,2), &wsaData) != 0)
		return;

	logfacility = facility;
	logident = strdup (ident);

	if (logident == NULL)
		return;

	if (option & LOG_PID) {
		void *tmp;
		size_t len = strlen (logident) + 100;
		tmp = realloc (logident, len);

		if (tmp == NULL) {
			free (logident);
			logident = NULL;
			return;
		}

		logident = tmp;

		sprintf (logident + strlen (logident), "[%u]", (unsigned int)GetCurrentProcessId ());
	}

	DWORD len = sizeof logsource;
	if (!GetComputerName (logsource, &len))
		logsource[0] = '\0';
}

void syslog (int priority, const char *format, ...)
{
	const char months[12][4] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" };
	char message[10248+50];
	SYSTEMTIME st;
	va_list args_list;
	int offset, offset2;

	openlogsocket();
	GetLocalTime (&st);

	if (logsocket == INVALID_SOCKET)
		return;

	offset = sprintf (message, "<%d>%s %2d %02d:%02d:%02d %s %s: ", logfacility + priority, months[st.wMonth - 1], st.wDay, st.wHour, st.wMinute, st.wSecond, logsource, logident);

	va_start (args_list, format);
	offset2 = _vsnprintf(message + offset, (sizeof (message) - offset) - 3, format, args_list);

	if (offset2 == -1)
		strcpy (message + sizeof (message) - 3, "\n");
	else
		strcpy (message + offset + offset2, "\n");

	va_end (args_list);

	sendto (logsocket, message, strlen (message), 0, (SOCKADDR *)&loghost, sizeof loghost);
}

#endif

int	write_to_log (uint8_t	_level,char	*_text, ...)
{
time_t _tt;
struct tm *_tm;
char	_logtext[ 10248 ];
va_list args_list;
#ifdef WIN32
HANDLE eventHandle;
#endif

	va_start ( args_list, _text );
#ifndef WIN32
	vsnprintf( _logtext, sizeof ( _logtext ) , _text, args_list );
	_logtext[sizeof (_logtext) - 1] = '\0';

	if (config.do_syslog == 1)
		syslog (_level, "%s", _logtext);
#else
	_vsnprintf( _logtext, sizeof ( _logtext ) , _text, args_list );
	_logtext[sizeof (_logtext) - 1] = '\0';

	if (config.do_syslog == 1)
		syslog (_level, "%s", _logtext);

	eventHandle = RegisterEventSource (NULL, "Millistream Database Application");

	if (eventHandle != NULL) {
		WORD wType = EVENTLOG_INFORMATION_TYPE;
		DWORD dwEventId = MDA_INFO;
		char *ar[1] = { _logtext };

		if (_level == LOG_ERR) {
			wType = EVENTLOG_WARNING_TYPE;
			dwEventId = MDA_WARNING;
		} else if (_level == LOG_CRIT) {
			wType = EVENTLOG_ERROR_TYPE;
			dwEventId = MDA_ERROR;
		}

		if (!ReportEvent (eventHandle, wType, 0, dwEventId, NULL, 1, 0, (const char **) ar, NULL))
			printf ("ReportEvent() failed: %lu\n", GetLastError ());

		DeregisterEventSource (eventHandle);
	} else if (config.silent == 0) {
		printf ("RegisterEventSource() failed: %lu\n", GetLastError ());
	}
#endif
	time (&_tt);
	_tm = localtime (&_tt);
	va_end ( args_list );

	if (config.silent == 0)
		printf ("%02d:%02d:%02d  %s\n",_tm->tm_hour, _tm->tm_min, _tm->tm_sec,_logtext);
	
	return 1;
}
void	write_sqllog(int queue, char *_text,...)
{
time_t	_tt;
struct	tm *_tm;
char	_logtext[ 10248 ];
va_list args_list;

	if(config.logsqlpath == NULL ) return;
	time(&_tt);
	_tm = localtime(&_tt);


	va_start ( args_list, _text );
#ifndef WIN32
	vsnprintf( _logtext, sizeof ( _logtext ) , _text, args_list );
#else
	_vsnprintf( _logtext, sizeof ( _logtext ) , _text, args_list );
#endif
	_logtext[sizeof (_logtext) - 1] = '\0';
	va_end ( args_list );
	if(config.currentday != _tm->tm_mday ) {
		if (config.fd_sqllog != NULL ) fclose(config.fd_sqllog);
		config.currentday = _tm->tm_mday;
		config.fd_sqllog = NULL;
	}
	if(!config.fd_sqllog) {
		char _filename[512];
#ifdef WIN32
		CreateDirectory(config.logsqlpath,NULL);
#else
		mkdir(config.logsqlpath,0755);
#endif
		sprintf(_filename,"%sSQ%02d%02d%02d.log",config.logsqlpath,(_tm->tm_year + 1900) % 100,_tm->tm_mon+1,_tm->tm_mday);
		config.fd_sqllog = fopen(_filename,"a");
		if(!config.fd_sqllog) return;
	}
	fprintf(config.fd_sqllog,"%02d:%02d:%02d [%d] %s\n", _tm->tm_hour, _tm->tm_min, _tm->tm_sec, queue, _logtext);
	return;
}

