#include "Syslog.h"
#include "define.h"
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
#include "terminal.h"
#include "WiFiCtrl.h"
#include "timer.h"

//#define SYSLOG_BUFFER_SIZE 1024
#define SYSLOG_BUFFER_SIZE 500
char mSyslogBuffer[SYSLOG_BUFFER_SIZE];
int mSyslogBufPtr;

int InitSyslog()
{
	mSyslogBufPtr = 0;
	memset(mSyslogBuffer,0,SYSLOG_BUFFER_SIZE);
	TimerStart(SYSLOG_TX_TIMER,SYSLOG_TX_TIMEOUT);
	
}


void SyslogTick()
{
	if(IsSyslogClientConnected() == 0)
	{
		mSyslogBufPtr = 0;
		return;
	}
	
	if(mSyslogBufPtr != 0 && IsTimerExpired(SYSLOG_TX_TIMER) == 1)
	{
		SendSyslogData(mSyslogBuffer,mSyslogBufPtr);
		mSyslogBufPtr = 0;
//		if(mSyslogBufPtr >= 150)
//		{
//			SendSyslogData(mSyslogBuffer,150);
//			mSyslogBufPtr -= 150;
//			
//		}
//		else
//		{
//			SendSyslogData(mSyslogBuffer,mSyslogBufPtr);
//			mSyslogBufPtr = 0;
//		}
		TimerStart(SYSLOG_TX_TIMER,SYSLOG_TX_TIMEOUT);
	}
	
}

int SyslogNewByte(char byte)
{    
	if(IsSyslogClientConnected() == 0)
	{
		mSyslogBufPtr = 0;
		return 0;
	}
	
	mSyslogBuffer[mSyslogBufPtr] = byte;
	mSyslogBufPtr++;
	
	if(mSyslogBufPtr == SYSLOG_BUFFER_SIZE)
	{
		SendSyslogData(mSyslogBuffer,SYSLOG_BUFFER_SIZE);
		mSyslogBufPtr = 0;
	}
	
	TimerStart(SYSLOG_TX_TIMER,SYSLOG_TX_TIMEOUT);
	return 1;
}

int SyslogNewString(char *string)
{
	if(IsSyslogClientConnected() == 0)
	{
		mSyslogBufPtr = 0;
		return 0;
	}
	
	SendSyslogData(string,strlen(string));
	return 1;
}

int SyslogIsBufferEmpty()
{
	if(mSyslogBufPtr == 0)
		return RET_OK;
	
	return RET_ERROR;
	
}