#include "CheckBox.h"

CheckBox::CheckBox(MenuManager* const pManager, const DWORD id) : GUIElement(pManager, id)
{
	m_pTex[0] = NULL;
	m_pTex[1] = NULL;

	m_pImage = new Image(GetManager(), 0);
	m_pImage->SetEventHandler(GE_BUTTONCLICK, OnImageClick);
	AddChild(m_pImage);
	m_pCaption = new Label(GetManager(), 0);
	m_pCaption->SetTextAlign(AL_LEFTCENTER);
	AddChild(m_pCaption);

	m_bChecked = false;
}

CheckBox::~CheckBox(void)
{
	m_pImage->SetTexture(NULL);
	SAFERELEASE(m_pTex[0]);
	SAFERELEASE(m_pTex[1]);
}

void CheckBox::SetSize(const float xl, const float yl)
{
	GUIElement::SetSize(xl, yl);

	m_pImage->SetSize(yl, yl);
	m_pCaption->SetPosition(yl + 2, 0);
	m_pCaption->SetSize(200, yl);
}

void CheckBox::SetTexture(DXTexture* const unchecked, DXTexture* const checked)
{ 
	m_pTex[0] = unchecked; 
	m_pTex[1] = checked;
	if (m_pTex[m_bChecked ? 1 : 0])
		m_pTex[m_bChecked ? 1 : 0]->IncRefCount();
	m_pImage->SetTexture(m_pTex[m_bChecked ? 1 : 0]); 
}

void CheckBox::SetChecked(const bool ck)
{
	if (ck != m_bChecked)
	{
		m_bChecked = ck;
		
		if (m_pTex[m_bChecked ? 1 : 0])
			m_pTex[m_bChecked ? 1 : 0]->IncRefCount();
		m_pImage->SetTexture(m_pTex[m_bChecked ? 1 : 0]); 
		HandleEvent(GE_VALUECHANGED, 0);
	}
}

void CheckBox::OnUpdate(void)
{
	if(IsEnable())
	{
		/*if(GetMouseButton(MBTN_LEFT))
		{
			m_pCaption->SetPosition(1,1);
			m_pImage->SetPosition(1,1);
		}
		else
		{
			m_pCaption->SetPosition(0,0);
			m_pImage->SetPosition(0,0);
		}*/
	}
}

void CheckBox::OnImageClick(GUIElement* const sender, const GUIEVENT evnt, void* pData)
{
	if (MBTN_LEFT == static_cast<MOUSEBUTTON>((unsigned)pData))
	{
		CheckBox* ck = dynamic_cast<CheckBox*>(sender->GetParent());

		if (ck && ck->IsEnable())
		{
			ck->SetChecked(!ck->m_bChecked);
		}
	}
}