//#include <FreeRTOS.h>
#include <stdio.h>
#include "Config/Include/APP_Config.h"
#include "Abstraction/Include/OS_Interface.h"
#include "Log.h"
static OS_TaskParam Param;

static void *loggerKey;
#define LOGGER_OUTPUT_TIMEROUT 200UL
#define LOG_ONE_TIME_LEN 	256
#define LOG_ERR_WRING_LEN 	128
char bufferOnLogger[LOG_ONE_TIME_LEN] = {0};

const char *const log_level_tag[JPCC_LOG_LEVEL_MAX] =
{
	"ERROR",
    "WARNING",
    "INFO",
    "DEBUG"
};

static void on_task_init()
{

}

static void on_recv_msg(uint16_t event_code, void* data, uint32_t data_size)
{
	( void ) event_code;
    ( void ) data;
	( void ) data_size;
}

static void on_recv_time_out()
{

}

static void on_loop()
{
    
}

void* LOG_getTaskParam()
{
    Param.queue_id = MSG_ID_LOG;
    Param.wait_time = 500;  //ms
    Param.task_init = on_task_init;
    Param.recv_msg = on_recv_msg;
    Param.time_out = on_recv_time_out;
    Param.loop = on_loop;
    return &Param;
}
void Log_Init(void)
{
	Uart_PORT_init();
	LPUART0_init();

}

void LoggerPrintf(char *fmt, ... )
{
	long int retlen = 0;
	va_list va;

	if(NULL == loggerKey)
	{
		loggerKey = OS_createLock();
	}

    // lock
	OS_lock(loggerKey);

	size_t length = strlen(bufferOnLogger);

	va_start(va, fmt);
	retlen = vsnprintf(bufferOnLogger + length, LOG_ONE_TIME_LEN - length, fmt, va);
	va_end(va);

	retlen += length;

	if(retlen == LOG_ONE_TIME_LEN) // content buffer is full
	{
		bufferOnLogger[retlen - 1] = '\0';
		bufferOnLogger[retlen - 2] = '\n';
		bufferOnLogger[retlen - 3] = '\r';
		retlen = LOG_ONE_TIME_LEN;
	}
	else if(retlen == LOG_ONE_TIME_LEN - 1  || retlen == LOG_ONE_TIME_LEN - 2 ) // content buffer is full
	{
	    bufferOnLogger[retlen] = '\0';
		bufferOnLogger[retlen - 1] = '\n';
		bufferOnLogger[retlen - 2] = '\r';
		retlen = LOG_ONE_TIME_LEN;
	}
	else if(retlen == LOG_ONE_TIME_LEN - 2) // content buffer is full
	{
	    bufferOnLogger[retlen - 1] = '\r';
	    bufferOnLogger[retlen] = '\n';
		bufferOnLogger[retlen + 1] = '\0';
		retlen = LOG_ONE_TIME_LEN;
	}
	else
	{
		bufferOnLogger[retlen] = '\r';
		bufferOnLogger[retlen + 1] = '\n';
		bufferOnLogger[retlen + 2] = '\0';
		retlen = retlen + 2;
	}

    // log output
    //LoggerOutPut(bufferOnLogger, retlen + 1);
	LPUART0_transmit_string( bufferOnLogger,retlen + 1);
	memset(bufferOnLogger,0,256);
	// unlock
	OS_unlock(loggerKey);
}


