#include "stdafx.h"
#include "FileModule.h"
#include "DataCenter.h"

CFileModule::CFileModule()
{
	m_fileHandle = fopen("dataFile.info", "a");
	m_errorHandle = fopen("errorFile.info", "a");
	memset(m_str, 0, 1024);
}

CFileModule::~CFileModule()
{
	
}

void CFileModule::HeartBeat_Imp()
{
	m_queMutex.acquire();
	int size = m_pduQueue.size();
	if (size == 0)
	{
		m_queMutex.release();
		return;
	}
	CInterProtocl *pdu = m_pduQueue.front();
	m_pduQueue.pop_front();
	m_queMutex.release();

	switch (pdu->m_eventType)
	{
	case EVENT_REQUEST:
		{
			DealOneRequestMsg(pdu);
		}
		break;
	case EVENT_RESPONSE:
		{
			DealOneResponseMsg(pdu);
		}
		break;
	}
	pdu->recycleITP();
}

void CFileModule::DealOneRequestMsg( CInterProtocl *pITP )
{	
	CTime tm; 
	tm = CTime::GetCurrentTime();
	m_strTime = tm.Format("%Y-%m-%d-%H-%M-%S");

	memset(m_str, 0, 1024);
	switch (pITP->m_operation)
	{
	case OP_WRITE_DATA:
		{		
			memcpy(m_str, pITP->m_data, pITP->m_nParam1);
			m_strOp.Format("%s", m_str);

			m_strData = "";
			if (pITP->m_len > pITP->m_nParam1)
			{
				CString str = "";
				char *buf = pITP->m_data + pITP->m_nParam1;
				int len = pITP->m_len - pITP->m_nParam1;
				for (int i=0; i<len; i++)
				{
					int d = *(buf+i) & 0xFF;
					str.Format("0x%02x", d);
					m_strData += " ";
					m_strData += str;
				}
			}

			m_strTotal = "";
			if (m_strData.IsEmpty())
			{
				m_strTotal = m_strTime + ": " + m_strOp + "\r\n";
			}
			else
			{
				m_strTotal = m_strTime + ": " + m_strOp + ": " + m_strData + "\r\n";
			}
			writeFile(1, m_strTotal.GetBuffer(), m_strTotal.GetLength());
		}
		break;
	}
}

void CFileModule::writeFile( int file, char *data, int len )
{
	switch (file)
	{
	case 1:
		{
			fwrite(data, len, 1, m_fileHandle);
			fflush(m_fileHandle);
		}
		break;
	case 2:
		{
			fwrite(data, len, 1, m_errorHandle);
			fflush(m_errorHandle);
		}
		break;
	}
}