#include "ComboBox.h"

ComboBox::ComboBox(MenuManager* const pManager, const DWORD id) : GUIElement(pManager, id)
{
	m_pInput = new Input(GetManager(), 0);
	AddChild(m_pInput);

	m_pButton = new Button(GetManager(), 0);
	AddChild(m_pButton);

	m_pDrop = new ListBox(GetManager(), 0);
	AddChild(m_pDrop);

	m_pInput->SetEventHandler(GE_BUTTONCLICK, OnOpenClick);
	m_pButton->SetEventHandler(GE_BUTTONCLICK, OnOpenClick);
	m_pDrop->SetVisible(false);

	m_pDrop->SetEventHandler(GE_VALUECHANGED, OnDropDownSel);
	m_pDrop->SetHightlightMouseItemEnable(true);

	m_SelectedIndex = -1;
}

ComboBox::~ComboBox(void)
{
}

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

	m_pInput->SetPosition(0, 0);
	m_pInput->SetSize(xl - yl, yl);
	m_pButton->SetSize(yl, yl);
	m_pButton->SetPosition(xl - yl, 0);
	m_pDrop->SetSize(xl - yl, m_pDrop->GetYl());
	m_pDrop->SetPosition(0, yl);
}

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

		if (cb && cb->IsEnable())
		{
			if (cb->m_pDrop->IsVisible())
				cb->m_pDrop->SetVisible(false);
			else
				cb->OpenDropDown();
		}
	}
}

void ComboBox::SetTexture(DXTexture* const input, const bool inputalphablend, const int inputborder, DXTexture* const btn, const bool btnalphablend, DXTexture* const drop, DXTexture* const dropsel, const bool dropalphablend, const int dropborder)
{
	m_pInput->SetTexture(input, inputalphablend, inputborder);
	m_pButton->SetTexture(btn);
	m_pButton->SetAlphaBlend(btnalphablend);
	m_pDrop->SetTexture(drop, dropsel, dropalphablend, dropborder);
}

void ComboBox::SetSelectedIndex(const int index) 
{ 
	if (m_SelectedIndex != index)
	{
		m_SelectedIndex = index;
		
		if (index >= 0 && index <= m_pDrop->GetItemCount())
			m_pInput->SetText(m_pDrop->GetItem(index));
		else
			m_pInput->SetText("");

		HandleEvent(GE_VALUECHANGED, 0);
	}
	m_pDrop->SetVisible(false);
}

void ComboBox::OpenDropDown(void)
{
	m_pDrop->SetVisible(true);
	m_pDrop->SetSelectedIndex(-1);
}

void ComboBox::OnDropDownSel(GUIElement* const sender, const GUIEVENT evnt, void* pData)
{
	ComboBox* cb = dynamic_cast<ComboBox*>(sender->GetParent());
	ListBox* lb = dynamic_cast<ListBox*>(sender);

	if (lb && cb && lb->GetSelectedIndex() >= 0)
	{
		cb->SetSelectedIndex(lb->GetSelectedIndex());
	}
}