#include "GUITextField.h"

GUITextField::GUITextField(int x, int y, int w, int h, const char *callback, int maxletters, const char *initialtext) : GUIElement(x, y, w, h, callback)
{
	this->widgetType = GUITEXTFIELD;
	this->text = initialtext;
	this->maxlen = maxletters;
}

void GUITextField::setHolderPointer(GUIHolder *holder)
{
	this->holder = holder;
	
	std::string t = "";
	for(int i=0; i<maxlen; i++)
	 t.append("A");

	int ww = holder->font->calculateWidth(t.c_str())+15;
	int hh = holder->font->calculateHeight(t.c_str())+8;

	if(w < ww) w = ww;
	if(h < hh) h = hh;
}



std::string GUITextField::checkKeyboardEvents(GUIKeyboardEvent &me) {
	
	if(me.pressed==false) 
		return "";

	if(strlen(me.key)==1)
	{
		char c = me.key[0];
		if(c=='\b')
			text = text.substr(0, text.length()-1);
		else
		if(text.length() < maxlen) 
		{
				text.append(me.key);
		}
	}
	
	return "_textfield";
}


void GUITextField::render(float dt)
{
	//super::render(d);
	this->GUIElement::render(dt);

	glLineWidth(2);
	glBegin(GL_LINE_STRIP);
		glVertex2i(x,	y);
		glVertex2i(x+w,	y);
		glVertex2i(x+w,	y+h);
		glVertex2i(x,	y+h);
		glVertex2i(x,	y);
	glEnd();

	if(text.length()!=0)
	if(holder!=0)
	{
		holder->font->setColor(1,1,1);
		holder->font->printCenteredXY(text.c_str(), x+w/2, y+h/2);
	}

}

