//#include "../../plat/smpp/src/include/smpp.h"
//#include "../../plat/debug/src/include/debug.h"
#include "smpp.h"
#include "debug.h"
#include "include/smeg_pub.h"

#define	SMEG_DEBUG_ID				8
#define	MAX_OUT_BUF_LEN		8192
#define	MAX_IN_BUF_LEN		1024
#define	SMEG_DEBUG				true

// upgrade to ubuntu 22.04 by simon at 2024/06/11
#define SMEG_MODULE_VERSION		"V1.0.02"
static BYTE log_flag = 0;
BYTE	smeg_debug_asciiIn[MAX_IN_BUF_LEN];
BYTE	smeg_debug_asciiOut[MAX_OUT_BUF_LEN];

static	BYTE	smeg_debug_status = 1;
static DWORD	smeg_status_id[20]	= 
{
		1,3,6,1,4,1,1373,1,1,2,3,1,2,SMEG_DEBUG_ID+2,1
};
static DWORD	smeg_version_id[20]	= 
{
		1,3,6,1,4,1,1373,1,1,2,3,1,2,SMEG_DEBUG_ID+2,2
};
static DWORD	smeg_ascii_in_id[20]	= 
{
		1,3,6,1,4,1,1373,1,1,2,3,1,2,SMEG_DEBUG_ID+2,3
};
static DWORD	smeg_ascii_out_id[20]	= 
{
		1,3,6,1,4,1,1373,1,1,2,3,1,2,SMEG_DEBUG_ID+2,4
};

void smeg_send_error(char *sdBuf);
void smeg_debugInit();
void smeg_list_smppLinkparam(int linkNo);
void smeg_debugTimer();

//---------
void smeg_debugInit()
{
	debug_set_response(15, smeg_status_id, &smeg_debug_status, 1);//smpp status
	debug_set_response(15, smeg_version_id, (BYTE*)SMEG_MODULE_VERSION, strlen(SMEG_MODULE_VERSION));
	debug_set_response(15, smeg_ascii_in_id, smeg_debug_asciiIn, MAX_IN_BUF_LEN);
	debug_set_response(15, smeg_ascii_out_id, smeg_debug_asciiOut, MAX_OUT_BUF_LEN);
}

void smeg_debugTimer()
{
	if (strlen((char*)smeg_debug_asciiIn) > 0)
	{
		if (strcmp((char*)(smeg_debug_asciiIn+1), "help") == 0)
		{
			smeg_send_ascout("SMEG Debug Monitor Help:\n\r\n\r");
			smeg_send_ascout("log none               Turn off all log items\n\r");
			smeg_send_ascout("log all                Turn on all log items\n\r");
		}
		else if (strcmp((char*)(smeg_debug_asciiIn+1), "log none") == 0)
		{
			log_flag = 0;
			smeg_send_ascout("Command OK!\n\r");
		} 
		else if (strcmp((char*)(smeg_debug_asciiIn+1), "log all") == 0) 
		{
			log_flag = 1;
			smeg_send_ascout("Command OK!\n\r");
		}
		else
		{
			smeg_send_error("Command Error.\n\r");
		}

		smeg_debug_asciiIn[0]	= '\0';
	}
}


void smeg_send_ascout(char *sdBuf)
{
	if (strlen(sdBuf)+strlen((char*)smeg_debug_asciiOut) < MAX_OUT_BUF_LEN)
	{
		strcat((char*)smeg_debug_asciiOut, sdBuf);
	}
}

void smeg_send_error(char *sdBuf)
{
	smeg_send_ascout("\x1b[31m");
	smeg_send_ascout(sdBuf);
	smeg_send_ascout("\x1b[0m");
}

static char smeg_debug_buf[8192];
void smeg_print(const char *fmt, ...)
{
	va_list ap;
	
	if(!log_flag)
		return;
		
	va_start(ap, fmt);
	vsprintf(smeg_debug_buf, fmt, ap);
	if((strlen((char*)smeg_debug_asciiOut) + strlen((char*)smeg_debug_buf)) < MAX_OUT_BUF_LEN)
		strcat((char*)smeg_debug_asciiOut, (char*)smeg_debug_buf);
	else
		strcpy((char*)smeg_debug_asciiOut, (char*)smeg_debug_buf);
	va_end(ap);
}

