#include "stdafx.h"
#include "QueueStrManager.h"
#include <stdio.h>
#include <windows.h>
#include <cstdio>
#include <process.h>
#include "ProcessRemodule.h"
#include "./system_basic_info/SystemAnalysis.h"

#pragma warning(disable: 4996)

QueueStrManager::QueueStrManager(void)
{
	m_pfunc = NULL;
	InitializeCriticalSectionAndSpinCount(&m_csQueueList, MAXCRITICALSECTIONSPINCOUNT);
}


QueueStrManager::~QueueStrManager(void)
{
	DeleteCriticalSection(&m_csQueueList);
	delete[] m_chr;
	m_chr = NULL;
	m_pfunc = NULL;
}

void QueueStrManager::AddString(const char * chr)
{
    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_100);
	EnterCriticalSection(&m_csQueueList);
	int vlen = strlen(chr);
	if(m_couter + 1 > m_max_couter || m_length + vlen + 1 > m_max_length){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_105);
		if(m_pfunc == NULL){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_106);
			LeaveCriticalSection(&m_csQueueList);
			return;
		}
		try
		{
			char* pchr = new char[m_max_length];
			strcpy(pchr, m_chr);
			//QueueUserWorkItem(m_pfunc, (LPVOID)pchr, WT_EXECUTEDEFAULT);
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_101);
			send_sql_message(pchr);

			memset(m_chr, 0, m_max_length);
			
			strcpy(m_chr, chr);
			m_couter = 1;
			m_length = strlen(chr);
			m_last_exec_time = ::GetCurrentTime();
		}
		catch(...){
			debug_print_syslog(0,"[allocate memory error] call AddString()");
		}
	}else {
		if(m_couter == 0){
			strcpy(m_chr, chr);
		}else {
			strcat(m_chr, chr);
		}
		m_couter++;
		m_length += strlen(chr);
	}
	LeaveCriticalSection(&m_csQueueList);
}

void QueueStrManager::Execute(bool bExit /*= true*/)
{
	// lihongzhen  2017/10/13 执行超过3秒的语句
	if(!bExit)
	{
		if(::GetCurrentTime() - m_last_exec_time < 3000)
		{
			return;
		}
	}

    LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_103);
	EnterCriticalSection(&m_csQueueList);
	if(m_length > 0){
		LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_107);
		if(m_pfunc == NULL){
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_108);
			LeaveCriticalSection(&m_csQueueList);
			return;
		}
		try
		{
			char* pchr = new char[m_length + 2]; // 预留结束符
			strcpy(pchr, m_chr);
			//QueueUserWorkItem(m_pfunc, (LPVOID)pchr, WT_EXECUTEDEFAULT);
			LOCATION_SYSTEM_BRANCH(LOCATION_SYSTEM_BRANCH_104);
			send_sql_message(pchr);

			m_last_exec_time = ::GetCurrentTime();
			memset(m_chr, 0, m_max_length);
			m_couter = 0;
			m_length = 0;
		}
		catch(...){

		}
	}
	LeaveCriticalSection(&m_csQueueList);
}
