#include "stdafx.h"
#include "TransLogger.h"

CTransLogger::CTransLogger()
{
}

CTransLogger::~CTransLogger()
{
}

HANDLE CTransLogger::m_hFile = INVALID_HANDLE_VALUE;


///////////////////////////////////////////////////////////////////////////////////////////
/// Operations
///////////////////////////////////////////////////////////////////////////////////////////

bool CTransLogger::Create(LPCTSTR lpszPathName, bool bOverwrite)
{
	if(m_hFile != INVALID_HANDLE_VALUE)
		return true;

    m_hFile = ::CreateFile(lpszPathName, GENERIC_WRITE, FILE_SHARE_READ, NULL, bOverwrite ? CREATE_ALWAYS : OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
	if(m_hFile == INVALID_HANDLE_VALUE)
		return false;

	if(!bOverwrite)
		::SetFilePointer(m_hFile, 0, NULL, FILE_END);

	return true;
}

bool CTransLogger::Close()
{
	if(m_hFile == INVALID_HANDLE_VALUE)
		return false;

	bool bClose = ::CloseHandle(m_hFile) ? true :false;
	m_hFile = INVALID_HANDLE_VALUE;

	return bClose;	
}

bool CTransLogger::Flush()
{
	if(m_hFile == INVALID_HANDLE_VALUE)
		return false;

	return ::FlushFileBuffers(m_hFile) ? true : false;
}

DWORD CTransLogger::Write(LPCTSTR lpszFormat, ...)
{
	if(m_hFile == INVALID_HANDLE_VALUE)
		return -1;

	TCHAR* pszMessage = NULL;
	DWORD dwSize = 0;

	va_list listArgument;
	va_start(listArgument, lpszFormat);
	dwSize = (DWORD)::_vsctprintf(lpszFormat, listArgument) + 1;

	pszMessage = new TCHAR[dwSize];
	::memset(pszMessage, NULL, dwSize);

	dwSize = (DWORD)::_vstprintf(pszMessage, lpszFormat, listArgument);
	va_end(listArgument);

	if(dwSize < 0)
	{
		delete [] pszMessage;
		return -1;
	}

	DWORD dwWritten = 0;
	bool bWritten = false;

	bWritten = ::WriteFile(m_hFile, pszMessage, dwSize, &dwWritten, NULL) ? true : false;
	if(bWritten)
		Flush();

	delete [] pszMessage;	

	return bWritten ? dwWritten : -1;
}