#include "pch.h"
#include "Config.h"
#include "OctalEditCtrl.h"


//////////////////////////////////////////////////////////////////////////
// COctalEdit

IMPLEMENT_DYNAMIC(COctalEdit, CEdit)

COctalEdit::COctalEdit()
    = default;

COctalEdit::~COctalEdit()
    = default;

BEGIN_MESSAGE_MAP(COctalEdit, CEdit)
	ON_WM_CHAR()
	ON_CONTROL_REFLECT(EN_UPDATE, &COctalEdit::OnEnUpdate)
END_MESSAGE_MAP()

void COctalEdit::OnChar(UINT nChar, UINT nRepCnt, UINT nFlags)
{
	if (nChar == VK_RETURN)
	{
		return; // запрет обработки по-умолчанию
	}

	// запрещаем цифры 8 и 9
	if (nChar == 0x38 || nChar == 0x39)
	{
		return;
	}

	CEdit::OnChar(nChar, nRepCnt, nFlags);
}

void COctalEdit::OnEnUpdate()
{
	if (m_pSpin)
	{
		if (!m_pSpin->isSpinChange())
		{
			CString str;
			const int nLen = GetWindowTextLength();
			GetWindowText(str.GetBufferSetLength(nLen), nLen + 1);
			str.ReleaseBuffer();
			const int value = Global::OctStringToWord(str);
			m_pSpin->SetPos32(value);
		}
	}
}


//////////////////////////////////////////////////////////////////////////
// COctSpinButtonCtrl

IMPLEMENT_DYNAMIC(COctSpinButtonCtrl, CSpinButtonCtrl)

COctSpinButtonCtrl::COctSpinButtonCtrl()
= default;

COctSpinButtonCtrl::~COctSpinButtonCtrl()
= default;


BEGIN_MESSAGE_MAP(COctSpinButtonCtrl, CSpinButtonCtrl)
	ON_NOTIFY_REFLECT(UDN_DELTAPOS, &COctSpinButtonCtrl::OnDeltapos)
END_MESSAGE_MAP()


void COctSpinButtonCtrl::SetOctBuddy(COctalEdit *pOctBuddy)
{
	m_pOctBuddy = pOctBuddy;
	m_pOctBuddy->AttachSpin(this);
}

void COctSpinButtonCtrl::OnDeltapos(NMHDR *pNMHDR, LRESULT *pResult)
{
	const auto pNMUpDown = reinterpret_cast<LPNMUPDOWN>(pNMHDR);
	CString str;
	int v = pNMUpDown->iPos + pNMUpDown->iDelta;
	int l = 0, u = 0;
	GetRange32(l, u);

	if (v > u)
	{
		v = u;
	}
	else if (v < l)
	{
		v = l;
	}

	m_bSpinChange = true;
	Global::WordToOctString(v, str);

	if (m_pOctBuddy)
	{
		m_pOctBuddy->SetWindowText(str);
	}

	m_bSpinChange = false;
	*pResult = 0;
}



