#include "Button.h"
#include "TouchControlsConfig.h"





using namespace touchcontrols;

Button::Button(std::string tag,RectF pos,std::string image_filename,int value_):
												ControlSuper(tag,pos)
{
	value = value_;
	image = image_filename;
	glTex = 0;
	id = -1;
	updateSize();
};

void Button::updateSize()
{
	glRect.resize(controlPos.right - controlPos.left, controlPos.bottom - controlPos.top);
}

void Button::setEnabled(bool v)
{
	enabled = v;
}


bool Button::processPointer(int action, int pid, float x, float y)
{
	if (action == P_DOWN)
	{
		if (controlPos.contains(x,y))
		{
			id = pid;
			signal_buttonDown.emit(value);
			signal_button.emit(1,value);
			return true;
		}
		return false;
	}
	else if (action == P_UP)
	{
		if (pid == id)
		{
			id = -1;
			signal_buttonUp.emit(value);
			signal_button.emit(0,value);
			return true;
		}
		return false;
	}
	else if(action == P_MOVE)
	{
		return false;
	}
}


bool Button::initGL()
{
	int x,y;
	glTex = loadTextureFromPNG(image,x,y);
}

bool Button::drawGL()
{
	drawRect(glTex,controlPos.left,controlPos.top,glRect);
}

void Button::saveXML(TiXmlDocument &doc)
{
	TiXmlElement * root = new TiXmlElement(tag);
	doc.LinkEndChild( root );

	ControlSuper::saveXML(*root);
}

void Button::loadXML(TiXmlDocument &doc)
{
	TiXmlHandle hDoc(&doc);
	TiXmlElement* pElem=hDoc.FirstChild( tag ).Element();

	if (!pElem) //Check exists, if not just leave as default
		return;

	ControlSuper::loadXML(*pElem);

}
