#include "text.h"
#include "video_int.h"
#include "video.h"
#include "storage.h"
#include "config.h"
#include "sceneobjectfabric.h"
#include "textrenderer.h"
#include <iostream>

ObjectFabric<TextObject> TextObjectFabric;

TextObject::TextObject()
	: SceneObject()
{}


TextObject::~TextObject()
{}


void TextObject::draw ( )
{
	Video_Interface *vid=video_get_interface ( _video_name_ );
	if ( !vid ) return;
	vid->_add_sprite ( _object_name_, _scene_name_ );
}

bool TextObject::load ( std::string storage_name, std::string storage_prefix, std::string scene_name, std::string object_name )
{
	if(!SceneObject::load(storage_name, storage_prefix, scene_name, object_name))return false;
	
	storage_prefix+="text->";
	Config_Interface *intf = config_get_interface ( storage_name );
	if ( !intf )
	{
		_set_error("Can't get config interface:"+config_error());
		return false;
	}
	_text_=intf->_get_value ( storage_prefix+"text", "" );
	_renderer_type_=intf->_get_value ( storage_prefix+"renderer", "" );
	_font_=intf->_get_value ( storage_prefix+"font", "" );
	_font_size_=atol(intf->_get_value ( storage_prefix+"font_size", "" ).c_str());
	
	_clr_.set_r(atol(intf->_get_value ( storage_prefix+"r_color", "" ).c_str()));
	_clr_.set_g(atol(intf->_get_value ( storage_prefix+"g_color", "" ).c_str()));
	_clr_.set_b(atol(intf->_get_value ( storage_prefix+"b_color", "" ).c_str()));
	_clr_.set_a(atol(intf->_get_value ( storage_prefix+"a_color", "" ).c_str()));
	
	Video_Interface *vid=video_get_interface ( _video_name_ );
	if ( !vid )
	{
		_set_error("Can't get video interface:"+video_error());
		return false;
	}

	Text_Renderer *renderer;
	renderer=textrenderer_get(_renderer_type_);
	if ( !renderer )
	{
		_set_error("Can't get renderer:"+textrenderer_error());
		return false;
	}
	if( !renderer->render_text_line ( _video_name_, _font_, _text_, _clr_, _font_size_, _object_name_, _scene_name_, true ))
	{
		_set_error("Can't render text:"+renderer->_get_error());
		return false;
	}
	if(!vid->_create_sprite(_object_name_, _scene_name_, _object_name_, _scene_name_, true))
	{
		_set_error("Can't create sprite: "+vid->_get_error());
		return false;
	}

	Video_Sprite *spr=vid->_get_sprite ( _object_name_, _scene_name_);
	if(!spr)
	{
		_set_error("Can't get sprite: "+vid->_get_error());
		return false;
	}
	
	_xb_=atof ( intf->_get_value ( storage_prefix+"x_base", "0.5" ).c_str() );
	_yb_=atof ( intf->_get_value ( storage_prefix+"y_base", "0.5" ).c_str() );
	spr->_set_base_point ( _xb_, _yb_ );
	spr->_set_coord(_x_, _y_);
	return true;
}

