// AsHexadecimalEdit.cpp : implementation file
//

#include "stdafx.h"
#include "AsHexadecimalEdit.h"

/*
#ifdef _DEBUG
#define new DEBUG_NEW
#undef THIS_FILE
static char THIS_FILE[] = __FILE__;
#endif
*/

/////////////////////////////////////////////////////////////////////////////
// CAsHexadecimalEdit

CAsHexadecimalEdit::CAsHexadecimalEdit():
	bitCount_(32)
{
}

CAsHexadecimalEdit::~CAsHexadecimalEdit()
{
}


BEGIN_MESSAGE_MAP(CAsHexadecimalEdit, CEdit)
	//{{AFX_MSG_MAP(CAsNumericEdit)
	ON_WM_CHAR()
	ON_CONTROL_REFLECT(EN_KILLFOCUS, OnKillfocus)
	//}}AFX_MSG_MAP
END_MESSAGE_MAP()

/////////////////////////////////////////////////////////////////////////////
// CAsNumericEdit message handlers

void CAsHexadecimalEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags) 
{
	if (nChar >= '0' && nChar <= '9' ||
			   nChar >= 'a' && nChar <= 'f' ||
			   nChar >= 'A' && nChar <= 'F' ||
			   nChar == VK_BACK ||
			   nChar == VK_LEFT	||
			   nChar == VK_RIGHT ||
			   nChar == VK_DELETE ) {
		
	} else if (nChar == VK_RETURN) {
		Validate();
	} else {
		// any other invalid char
		//
		return;
	}
	
	CEdit::OnChar(nChar, nRepCnt, nFlags);
}


void CAsHexadecimalEdit::SetBitCount(long bitCount)
{
	if (bitCount < 1)
		bitCount = 1;
	else if (bitCount > 32)
		bitCount = 32;

	bitCount_ = bitCount;
}

long CAsHexadecimalEdit::GetBitCount() const
{
	return bitCount_;
}

long CAsHexadecimalEdit::GetValue()
{
	return Validate();
}

long CAsHexadecimalEdit::Validate()
{
	CString tmp;
	long value;

	GetWindowText(tmp);

	value = ValidateString(tmp);

	tmp = FormatValue(value);
		
	SetWindowText(tmp);

	return value;
}

void CAsHexadecimalEdit::OnKillfocus() 
{
	Validate();	
}

long CAsHexadecimalEdit::ValidateString(const CString& valueStr)
{
	long value;

	if (valueStr.GetLength())
		sscanf((const char*)valueStr, "%08X", &value);
	else
		value = 0;

	return ValidateValue(value);
}

long CAsHexadecimalEdit::ValidateValue(long value)
{
	value &= (0xffffffff >> (32 - bitCount_));
	
	return value;
}

CString CAsHexadecimalEdit::FormatValue(long value)
{
	CString tmp;
	
	value = ValidateValue(value);
	tmp.Format("%08X", value);

	return tmp;
}

void CAsHexadecimalEdit::SetValue(long value)
{
	value = ValidateValue(value);

	SetWindowText(FormatValue(value));
}
