#include "log_process_module.h"
#include <iostream>
#include <time.h>
#include <string.h>

#pragma warning(disable:4267)
#pragma warning(disable:4996)

using namespace std;

log4cpp::Appender *appender[LOG_FILE_NUM];
log4cpp::Layout *layout[LOG_FILE_NUM];
log4cpp::Category* category[LOG_FILE_NUM];
char* log_file_name[LOG_FILE_NUM]     = {"./sys/syslog.txt"};
char* log_appender_name[LOG_FILE_NUM] = {"syslog"};
char* log_category_name[LOG_FILE_NUM] = {"syslog"};

int log_module_init(void)
{
	UINT32 i = 0;
	system("mkdir sys");
	for(i=0; i<LOG_FILE_NUM; i++)
	{
		//appender[i] = new log4cpp::FileAppender(log_appender_name[i], log_file_name[i]);
		appender[i] = new log4cpp::RollingFileAppender("runing_sys_log", log_file_name[i], ROLLING_LOG_FILE_SIZE, ROLLING_LOG_FILE_NUM);
		layout[i] = new log4cpp::SimpleLayout();
		category[i] = &(log4cpp::Category::getInstance(log_category_name[i]));
		appender[i]->setLayout(layout[i]);
        category[i]->setAppender(appender[i]);
        category[i]->setPriority(log4cpp::Priority::INFO);
	}
	return 0;
}

int sys_log_print(UINT debugLevel, UINT logFileIndex, char* logStr)
{
    if(NULL == logStr)
    {
        return 0;
    }
	char buffer[LOG_BUF_SIZE + 50] = {0};
	
    const time_t t = time(NULL);	
	struct tm* current_time = localtime(&t);

    sprintf(buffer, "[%4d-%02d-%02d %02d:%02d:%02d]", 
		current_time->tm_year + 1900,
		current_time->tm_mon + 1,
		current_time->tm_mday,
		current_time->tm_hour,
        current_time->tm_min,
        current_time->tm_sec);
	strcat (buffer, logStr);

	switch (debugLevel)
	{
		case SYS_LOG_INFO:
			category[logFileIndex]->info(buffer);
			break;
		case SYS_LOG_WARNING:
			category[logFileIndex]->warn(buffer);
			break;
		case SYS_LOG_ERROR:
			category[logFileIndex]->error(buffer);
			break;
		default:		
	    category[logFileIndex]->info(buffer);
	}
	return 0;
}

int debug_print(UINT debugLevel, char* logStr)
{
    sys_log_print(debugLevel, 0, logStr);
    return 0;
}


