#include "stdafx.h"
#include "Application.h"

Application::Application()
	: m_logfile( NULL )
{
	m_logfile = new Logger( "log.txt" );
}

Application::~Application()
{
	if( m_logfile )
	{
		delete m_logfile;
		m_logfile = NULL;
	}
}

BOOL Application::InitInstance( HINSTANCE hInstance, int argc, LPWSTR *argv )
{
	m_hInstance = hInstance;

	if( !SetupInstance( argc, argv ) )
	{
		Log( "Creating instance failed.\n" );
		return FALSE;
	}

	return TRUE;
}

void Application::Shutdown()
{
	if( m_classAtom )
	{
		UnregisterClass( (LPCWSTR)MAKELONG( m_classAtom, 0 ), m_hInstance );
	}
	m_hInstance = NULL;
}

int Application::Run()
{
	return 0;
}

void Application::Log( const char *msg )
{
	if( m_logfile )
	{
		m_logfile->WriteLine( msg );
	}
}

void Application::Log( const wchar_t *msg )
{
	int len;
	len = WideCharToMultiByte( CP_ACP, 0, msg, -1, NULL, 0, NULL, NULL );
	char* buf = new char[len];
	WideCharToMultiByte( CP_ACP, 0, msg, len, buf, len, NULL, NULL );
	Log( buf );
	delete [] buf;
}

void Application::LogEx( const char *fmt, ... )
{
	char szBuf[512];
	memset( szBuf, 0, 512 * sizeof( char ) );

	try
	{
		va_list args;
		va_start( args, fmt );
		vsnprintf ( szBuf, 512, fmt, args ); // C4996
		va_end( args );

		Log( szBuf );
	}
	catch( ... )
	{
	}
}

void Application::LogEx( const wchar_t *fmt, ... )
{
	wchar_t szBuf[512];
	memset( szBuf, 0, 512 * sizeof( wchar_t ) );

	try
	{
		va_list args;
		va_start( args, fmt );
		_vsnwprintf ( szBuf, 512, fmt, args ); // C4996
		va_end( args );

		Log( szBuf );
	}
	catch( ... )
	{
	}
}

BOOL Application::RegisterWindowClass( WNDCLASSEX* wc )
{
	m_classAtom = RegisterClassEx( wc );
	return m_classAtom != 0;
}

BOOL Application::LoadConfiguration()
{
	return TRUE;
}

BOOL Application::SetupInstance( int argc, LPWSTR *argv )
{
	return TRUE;
}

BOOL Application::HandleKeyDown( WPARAM wParam, LPARAM lParam )
{
	return TRUE;
}
