#include "textrenderer.h"
#include "storage.h"
#include "dynamic.h"

#include <string>

#ifdef Revision
#undef Revision
#endif
#define Revision "me_textrenderer.cpp $Revision: 1.2 $"

#ifdef HAVE_CONFIG_H
#include <conf_config.h>
#endif

#include <iostream>

static Storage<std::string, Text_Renderer*> _renderers;
static std::string last_error;

bool textrenderer_create ( std::string name, std::string driver, bool replace )
{
	if ( _renderers.exist ( name ) )
	{
		if ( replace )
		{
			Text_Renderer *z;
			z=_renderers.get ( name );
			delete z;
			_renderers.remove ( name );
		}
		else
		{
			last_error = name + " already exist";
			return false;
		}
	}
	if ( !module_load ( driver ) )
	{
		last_error = dynamic_error();
		return false;
	}
	Dynamic_Module *mod;
	if ( ( mod = module_get ( driver ) ) == 0 )
	{
		last_error = dynamic_error();
		return false;
	}
	if ( !mod->_symbol_load ( "_get_textrenderer" ) )
	{
		module_remove ( driver );
		last_error = dynamic_error();
		return false;
	}
	Text_Renderer* ( *fun ) ( void );
	if ( ( fun = ( Text_Renderer * ( * ) ( void ) ) ( *mod ) [ "_get_textrenderer" ] ) == 0 )
	{
		mod->_symbol_remove ( "_get_textrenderer" );
		module_remove ( driver );
		last_error = dynamic_error();
		return false;
	}
	Text_Renderer *intf;
	intf=fun();
	if ( !intf->_init() )
	{
		mod->_symbol_remove ( "_get_textrenderer" );
		module_remove ( driver );
		return false;
	}
	last_error="";
	std::cerr<<"Renderer "<<name<<" loaded from file "<<driver<<std::endl;
	return _renderers.insert ( name, intf );
}

bool textrenderer_remove ( std::string name )
{
	last_error="";
	if ( !_renderers.exist ( name ) ) return true;
	Text_Renderer *z;
	z=_renderers.get ( name );

	Dynamic_Module *mod;
	if ( ( mod = module_get ( z->_get_driver_name() ) ) == 0 )
	{
		last_error = dynamic_error();
	}
	else mod->_symbol_remove ( "_get_textrenderer" );
	module_remove ( z->_get_driver_name() );
	return _renderers.remove ( name );
}
Text_Renderer* textrenderer_get ( std::string renderer_name )
{
	if ( !_renderers.exist ( renderer_name ) ) return 0;
	return _renderers.get ( renderer_name );
}
std::string textrenderer_error( )
{
	return last_error;
}
std::string textrenderer_version( )
{
	return VERSION;
}

