




#include <flare_gui/text_box.h>
#include <flare_gui/collision_box.h>
#include <boost/algorithm/string.hpp>





FGUITextBox::word_width_pair::word_width_pair(std::string word, int width)
	: word(word)
	, width(width)
{}





FGUITextBox::FGUITextBox(FGUIParent *parent, ALLEGRO_FONT *font, std::string text, float x, float y, float width, float height)
	: FGUIWidget(parent, new FGUICollisionBox(x, y, width, height))
	, font(font)
	, text(text)
{
	create_word_width_pairs(text, font);
}





void FGUITextBox::create_word_width_pairs(std::string text, ALLEGRO_FONT *font)
{
	word_width_pairs.clear();

	std::vector<std::string> word;

	//#include <boost/algorithm/string.hpp>
	boost::split(word, text, boost::is_any_of("\t \n\r")); ////// TODO:
															///// NOTE NOTE NOTE!!1
														   ////// THIS is the ONLY occourance of a boost function in
															///// flare_gui, requiring the inclusion of boost
															///// it should be replaced with an inhouse function

	for (int i=0; i<(int)word.size(); i++)
	{
		word_width_pairs.push_back(word_width_pair(word[i], al_get_text_width(font, word[i].c_str())));
	}
}





void FGUITextBox::set_text(std::string text)
{
	this->text = text;
	this->create_word_width_pairs(text, font);
}





void FGUITextBox::on_draw()
{
	// this is without letter-spacing

	float width_of_space = al_get_text_width(font, " ");
	float x_cursor = 0;
	float y_cursor = 0;
	float next_x = 0;
	float width = gimmie_placement()->w;
	float line_height = al_get_font_line_height(font);

	for (int i=0; i<(int)word_width_pairs.size(); i++)
	{
		next_x = x_cursor + word_width_pairs[i].width;
		if (next_x > width)
		{
			x_cursor = 0;
			y_cursor += line_height;
		}
		al_draw_text(font, text_color, x_cursor, y_cursor, NULL, word_width_pairs[i].word.c_str());
		x_cursor = x_cursor + word_width_pairs[i].width + width_of_space;
	}
}
