/*--------------------------------------------------------------------
 * FILE:
 *     show.c
 *
 * NOTE:
 *     This file is composed of the logging and debug functions
 *
 * Portions Copyright (c) 2003-2006, Atsushi Mitani
 *--------------------------------------------------------------------
 */
#include <stdio.h>
#include <stdarg.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <time.h>
#include <sys/time.h>
#include <sys/types.h>

#define TIMESTAMP_SIZE 19		/* format `YYYY-MM-DD HH:MM:SS' */

/*--------------------------------------
 * PROTOTYPE DECLARATION
 *--------------------------------------
 */
void show_debug(const char * fmt,...);
void show_error(const char * fmt,...);
void PGRwrite_log_file(FILE * fp, const char * fmt,...);

extern int Debug_Print;
extern int Log_Print;
extern FILE * LogFp;

static char*
get_current_timestamp(void)
{
	time_t now;
	static char buf[TIMESTAMP_SIZE + 1];

	now = time(NULL);
	strftime(buf, sizeof(buf),
		 "%Y-%m-%d %H:%M:%S", localtime(&now));
	return buf;
}

void
show_debug(const char * fmt,...)
{
	va_list ap;
	char *timestamp;

	if (Debug_Print)
	{
		timestamp = get_current_timestamp();
		fprintf(stdout,"%s [%d] DEBUG:",timestamp, getpid());
		va_start(ap,fmt);
		vfprintf(stdout,fmt,ap);
		va_end(ap);
		fprintf(stdout,"\n");
		fflush(stdout);
	}
}

void
show_error(const char * fmt,...)
{
	va_list ap;
	char buf[256], *timestamp;

	if (Debug_Print)
	{
		timestamp = get_current_timestamp();
		fprintf(stderr,"%s [%d] ERROR:",timestamp, getpid());
		va_start(ap,fmt);
		vfprintf(stderr,fmt,ap);
		va_end(ap);
		fprintf(stderr,"\n");
		fflush(stderr);
	}
	if ((Log_Print) && (LogFp != NULL))
	{
		va_start(ap,fmt);
		vsnprintf(buf,sizeof(buf),fmt,ap);
		va_end(ap);
		PGRwrite_log_file(LogFp,buf);
	}
}

void
PGRwrite_log_file(FILE * fp, const char * fmt,...)
{
	char buf[256];
	char log[288];
	char * p;
	va_list ap;
	time_t t;

	if (fp == NULL)
	{
		return;
	}
	if (time(&t) < 0)
	{
		return;
	}
	snprintf(log,sizeof(log),"%s ",ctime(&t));
	p = strchr(log,'\n');
	if (p != NULL)
	{
		*p = ' ';
	}
	va_start(ap,fmt);
	vsnprintf(buf,sizeof(buf),fmt,ap);
	va_end(ap);
	strcat(log,buf);
	strcat(log,"\n");
	if (fputs(log,fp) >= 0)
	{
		fflush(fp);
	}
}

