#include "Slider.h"

#include "MenuManager.h"

Slider::Slider(MenuManager* const pManager, const DWORD id) : GUIElement(pManager, id)
{
	m_Value = 0;
	m_Min = 0;
	m_Max = 100;

	m_bDragNob = false;
	m_DragOffset = 0;

	m_pBar = new Image(GetManager(), 0);
	AddChild(m_pBar);
	m_pNob = new Image(GetManager(), 0);
	m_pNob->SetEventHandler(GE_BUTTONDOWN, OnNobMouseDown);
	AddChild(m_pNob);
}

Slider::~Slider(void)
{
}

void Slider::OnUpdate(void)
{
	if (m_bDragNob)
	{
		if (!GetManager()->GetInputDevice()->GetMouseButton(MBTN_LEFT))
		{
			m_bDragNob = false;
		}
		else
		{
			float nobpos = GetManager()->GetInputDevice()->GetCursorX() - GetDrawPos().x - m_DragOffset;
			
			int newvalue = 0.5f + m_Min + (nobpos + m_pNob->GetXl() / 2.0f - m_NobOffset) / (GetXl() - m_NobOffset * 2) * (m_Max-m_Min); //+0.5f to round
			
			if (newvalue < m_Min)
				newvalue = m_Min;
			else if (newvalue > m_Max)
				newvalue = m_Max;

			SetValue(newvalue);
		}
	}
}

void Slider::SetSize(const float xl, const float yl)
{
	GUIElement::SetSize(xl, yl);
	
	m_pBar->SetSize(xl, m_pBar->GetYl());

	SetImagePos();	
	SetNobPos();
}
	
void Slider::SetSliderSize(const float sliderheight, const float nobxl, const float nobyl, const float nobsideoffset)
{
	m_pBar->SetSize(GetXl(), sliderheight);
	m_pNob->SetSize(nobxl, nobyl);

	SetImagePos();

	m_NobOffset = nobsideoffset;

	SetNobPos();
}

void Slider::SetRange(const int min, const int max)
{
	m_Min = min;
	m_Max = max;
	SetNobPos();
}

void Slider::SetValue(const int value)
{
	if (value != m_Value)
	{
		m_Value = value;
		SetNobPos();
		HandleEvent(GE_VALUECHANGED, 0);
	}
}

void Slider::SetImagePos(void)
{
	m_pBar->SetPosition(0, (GetYl() - m_pBar->GetYl()) / 2.0f);
	m_pNob->SetPosition(0, (GetYl() - m_pNob->GetYl()) / 2.0f);
}

void Slider::SetNobPos(void)
{
	m_pNob->SetPosition(m_NobOffset + (GetXl()-m_NobOffset*2) * ((m_Value - m_Min)/(float)(m_Max-m_Min)) - m_pNob->GetXl()/2, m_pNob->GetY());
}

void Slider::OnNobMouseDown(GUIElement* const sender, const GUIEVENT evnt, void* pData)
{
	if (MBTN_LEFT == static_cast<MOUSEBUTTON>((unsigned)pData))
	{
		Slider* sl = dynamic_cast<Slider*>(sender->GetParent());
		if (sl && sl->IsEnable())
		{
			sl->m_DragOffset = sl->GetManager()->GetInputDevice()->GetCursorX() - sl->m_pNob->GetDrawPos().x;
			sl->m_bDragNob = true;
		}
	}
}