#include "RadioButton.h"

RadioButton::RadioButton(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;
}

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

void RadioButton::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 RadioButton::SetTexture(DXTexture* const unchecked, DXTexture* const checked)
{ 
	m_pTex[0] = unchecked; 
	m_pTex[1] = checked;
	m_pTex[m_bChecked ? 1 : 0]->IncRefCount();
	m_pImage->SetTexture(m_pTex[m_bChecked ? 1 : 0]); 
}

void RadioButton::OnUpdate(void)
{
	if(IsEnable())
	{
	}
}

void RadioButton::SetChecked(const bool ck)
{
	if (ck)
	{
		GUIElement* par = GetParent();
		if (par)
		{
			FOREACH(el, par->GetChilds(), GUIElement)
			{
				if (el->GetInfo() != this)
				{
					RadioButton* rd = dynamic_cast<RadioButton*>(el->GetInfo());
					if (rd)
					{
						rd->SetChecked(false);
					}
				}
			}
		}
		m_bChecked = true;

		if (m_pTex[1])
			m_pTex[1]->IncRefCount();
		m_pImage->SetTexture(m_pTex[1]); 

		HandleEvent(GE_VALUECHANGED, 0);
	}
	else
	{
		if (ck != m_bChecked)
		{
			m_bChecked = false;
			
			if (m_pTex[0])
				m_pTex[0]->IncRefCount();
			m_pImage->SetTexture(m_pTex[0]); 

			HandleEvent(GE_VALUECHANGED, 0);
		}
	}
}

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

		if (rd && rd->IsEnable() && !rd->IsChecked())
		{
			rd->SetChecked(true); //use setter to uncheck all other radiobuttons in same container
		}
	}
}