/**
* @file common_itk_util.cpp
* @brief itk warpper utility function
* @author James
* @history
* ===================================================================================
* Date             Name                   Description of Change
* 18-July-2008     Ray
*/
#define _CRT_SECURE_NO_WARNINGS
#include <tc/tc_util.h>
#include <tc/tc_arguments.h>

#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include <time.h>
//
#ifdef WIN32
#include <io.h>
#include <direct.h>
#else
#endif
//
#include "tc_log.h"

#define ARGS_LENGTH 200
#define MAX_PRINTLINE_LENGTH 2000
#define MAX_PATH_LENGTH 2000
#define MAX_ARGUMENT_LENGTH 400
#define MAX_PARAMNAME_LENGTH 50
#define MAX_FILE_EXT_LENGTH 10
#define TRUE_FLAG 1
#define FALSE_FLAG 0
#define DETAILLOG 1

#define DOFREE(obj)								\
{												\
	if(obj)										\
	{											\
		MEM_free(obj);							\
		obj = NULL;								\
	}											\
}



FILE* logFile = NULL;

void CreateLogFile(char* logFileName)
{
	int i = 0;
	logFile = NULL;
	//get logFileName
	sprintf(logFileName, "%s", logFileName);
	printf("log file name: %s\n", logFileName);
	//create log file
	if ((logFile = fopen(logFileName, "w")) == NULL)
	{
		printf("log file create failed\n");
	}

}

void WriteLog(const char* format, ...)
{
	va_list arg;
	char tmp[MAX_PRINTLINE_LENGTH];
	struct tm *p;
	time_t now;
	time(&now);
	p = localtime(&now);
	char now_time[128] = "\0";

	sprintf_s(now_time, "[ %d-%d-%d %d:%02d:%02d ]", 1900 + p->tm_year, p->tm_mon + 1, p->tm_mday, p->tm_hour, p->tm_min,p->tm_sec);

	if (logFile)
	{
		//get the message
		memset(tmp, 0, sizeof(tmp));
		va_start(arg, format);
		vsprintf(tmp, format, arg);
		va_end(arg);

		//----------print to command window for trace--------//
		printf("%s\n", tmp);

		//print message to log file
		fprintf(logFile, "%s %s\n", now_time, tmp);
		fflush(logFile);
	}
	else
	{
		printf("*!Error!*: Log File Not Exist\n");
	}
}

void CloseLog(void)
{
	if (logFile)
	{
		fclose(logFile);
		logFile = NULL;
	}
}



void CreateLogFile_jk(char* logFileName)
{
	int i = 0;

	logFile = NULL;


	//get logFileName
	sprintf(logFileName, "%s", logFileName);
	printf("log file name: %s\n", logFileName);


	//create log file
	if ((logFile = fopen(logFileName, "w")) == NULL)
	{
		printf("log file create failed\n");
	}

}

void WriteLog_jk(const char* format, ...)
{
	va_list arg;
	char tmp[MAX_PRINTLINE_LENGTH];

	if (logFile)
	{
		//get the message
		memset(tmp, 0, sizeof(tmp));
		va_start(arg, format);
		vsprintf(tmp, format, arg);
		va_end(arg);

		//----------print to command window for trace--------//
		printf("%s\n", tmp);

		//print message to log file
		fprintf(logFile, "%s\n", tmp);
		fflush(logFile);
	}
	else
	{
		printf("*!Error!*: Log File Not Exist\n");
	}
}

void CloseLog_jk(void)
{
	if (logFile)
	{
		fclose(logFile);
		logFile = NULL;
	}
}
