/* -----------------------------------------------------------------------------
	GSFramework
	Copyright 2001-2013 Emmanuel Julien. All Rights Reserved.
----------------------------------------------------------------------------- */


		#include "font/font_cache.h"
		#include "font/font_extended.h"
		#include "filesystem/filesystem.h"
		#include "platform.h"
		#include "log/log.h"

		using namespace GS;


//------------------------------------------------------------------------------
FontEx				*FontCache::GetFont(const char *name) const
{
	ListForeachPtr(FontAlias *, alias, font_aliases)
		if	(alias->font->GetName() == name)
			return alias->font;

	return NULL;
}
FontAlias			*FontCache::GetAlias(const char *alias) const
{
	ListForeachPtr(FontAlias *, font, font_aliases)
		if	(font->alias == alias)
			return font;
	return NULL;
}
FontEx				*FontCache::GetAliasedFont(const char *alias) const
{
	FontAlias *fa = GetAlias(alias);
	return fa ? fa->font.c_ptr() : NULL;
}
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
FontEx				*FontCache::LoadFont(const char *path, const char *alias)
{
	// Look for an already loaded instance of the font.
	FontEx *font = GetFont(path);

	// If font is not available, load it.
	if	(font == NULL)
	{
		IFont *base_font = font_factory->LoadFont(path);
		if	(base_font == NULL)
			return NULL;

		// Wrap with an extended font.
		font = new FontEx(base_font);
	}

	// Format default alias if none provided.
	String _alias(path);
	_alias.FileCutPathAndExtension();
	if	(!alias)
		alias = _alias;

	// Drop current alias if existing.
	FontAlias *font_alias = GetAlias(alias);
	if	(font_alias)
		font_aliases.Remove(font_alias);

	// Create the alias.
	font_alias = new FontAlias;
	font_alias->alias = alias;
	font_alias->font = font;

	font_aliases.Add(font_alias);

	__LOG__ << "Created a new font alias from '" << path << "' to '" << alias << "'.\n";
	return font;
}
void				FontCache::DeleteAlias(const char *alias)
{
	ListForeachPtr(FontAlias *, a, font_aliases)
		if	(a->alias == alias)
			font_aliases.Remove(a);
}
void				FontCache::DeleteAllFont()
{
	font_aliases.Clear();
}
//------------------------------------------------------------------------------

FontCache::~FontCache()
{
	// [EJ] Get rid of the fonts before the factory.
	DeleteAllFont();
}
