//Copyright (C) 2007 SiegeLord
//See ReadMe.txt and License.txt for copying information

#include "../include/engine/font.h"
#include "../include/engine/error.h"
#include "../include/engine/bitmap.h"

map<string, FONT*> g_mFonts;

FONT* FindFont(const char* filename)
{
	map<string, FONT*>::iterator it;
	it = g_mFonts.find(string(filename));

	if(it == g_mFonts.end())//can't find it, so load a new one
	{
		FONT* ret = ForceLoadFont(filename);

		g_mFonts.insert(pair<string, FONT*>(string(filename), ret));

		return ret;
	}
	else//return the existing one
	{
		return it->second;
	}
}


FONT* ForceLoadFont(const char* filename)
{
	FONT* ret = 0;

	FONT* temp = LoadAllegFont(filename);

	if(temp != 0)
	{
		ret = allegro_gl_convert_allegro_font_ex(temp, AGL_FONT_TYPE_TEXTURED, 1.0f, GL_ALPHA8);
		destroy_font(temp);
	}
	if(!ret)
		Throw("Could not load font:\n", filename);

	return ret;
}

FONT* LoadAllegFont(const char* filename)
{
	FONT* ret = 0;

	BITMAP* bmp = 0;
	bmp = LoadAllegBitmap(filename);
	if(bmp)
	{
		ret = grab_font_from_bitmap(bmp);
		destroy_bitmap(bmp);
	}
	if(!ret)
		Throw("Could not load font:\n", filename);

	return ret;
}

void FreeFonts()
{
	map<string, FONT*>::iterator it = g_mFonts.begin();

	while(it != g_mFonts.end())
	{
		allegro_gl_destroy_font(it->second);
		it++;
	}
}

//int GetTextLength(const char* text, FONT* fnt)
//{
//	FONT* old_font = font;
//	font = fnt;
//	int ret = gui_strlen(text);
//	font = old_font;
//	return ret;
//}
