// LogCtrl.cpp: implementation of the CLogCtrl class.
//
//////////////////////////////////////////////////////////////////////

#include "LogCtrl.h"

//////////////////////////////////////////////////////////////////////
// Construction/Destruction
//////////////////////////////////////////////////////////////////////

CLogCtrl::CLogCtrl()
{
	m_hwndEdit = NULL;

	m_ptPosition.x = 0;
	m_ptPosition.y = 0;

	m_ptSize.x = 0;
	m_ptSize.y = 0;
}


CLogCtrl::~CLogCtrl()
{
	if( m_hwndEdit )
	{
		DestroyWindow( m_hwndEdit );
	}
}


void CLogCtrl::Init( long x, long y, long width, long height, HWND hwndParent )
{
	//CreateFont(  )

	if( NULL == m_hwndEdit )
	{
		m_hwndEdit = CreateWindow( "EDIT", "", WS_VISIBLE | WS_CHILD | WS_BORDER | ES_READONLY | ES_MULTILINE | WS_VSCROLL | ES_AUTOVSCROLL,
			x, y, width, height, hwndParent, NULL, NULL, 0 );

		m_ptPosition.x = x;
		m_ptPosition.y = y;

		m_ptSize.x = width;
		m_ptSize.y = height;
	}
	else
	{
		SetParent( m_hwndEdit, hwndParent );

		SetPosition( x, y );
		SetSize( width, height );
	}
}

void CLogCtrl::SetPosition( long x, long y )
{
	m_ptPosition.x = x;
	m_ptPosition.y = y;

	if( m_hwndEdit )
	{
		SetWindowPos( m_hwndEdit, NULL, x, y, 0, 0, SWP_NOSIZE | SWP_NOZORDER );
	}
}

void CLogCtrl::SetSize( long width, long height )
{
	m_ptSize.x = width;
	m_ptSize.y = height;

	if( m_hwndEdit )
	{
		SetWindowPos( m_hwndEdit, NULL, 0, 0, width, height, SWP_NOMOVE | SWP_NOZORDER );
	}
}

void CLogCtrl::OutputMessage( const char* szMsg )
{
	if( NULL == m_hwndEdit )
	{
		return;
	}

	long lSelBegin, lSelEnd;
	long lTextLen;

	static char szTmp[300];

	int nCnt = 0, nDestCnt = 0;
	while( '\0' != szMsg[nCnt] && nDestCnt < 299 )
	{
		if( '\n' == szMsg[nCnt] )
		{
			szTmp[nDestCnt++] = '\r';

			if( nDestCnt == 299 )
			{
				break;
			}
		}

		szTmp[nDestCnt++] = szMsg[nCnt++];
	}
	szTmp[nDestCnt] = '\0';


	// get current selection
	SendMessage( m_hwndEdit, EM_GETSEL, (WPARAM)&lSelBegin, (LPARAM)&lSelEnd );

	// set selection at the end of the text
	lTextLen = SendMessage( m_hwndEdit, WM_GETTEXTLENGTH, 0, 0 );
	SendMessage( m_hwndEdit, EM_SETSEL, lTextLen, lTextLen );
	// add text(replace selection) at the end of the tex
	SendMessage( m_hwndEdit, EM_REPLACESEL, FALSE, (LPARAM)szTmp );

	// restore the selection
	SendMessage( m_hwndEdit, EM_SETSEL, lSelBegin, lSelEnd );
}