#include "sceneimage.h"
#include "video_int.h"
#include "video.h"
#include "storage.h"
#include "config.h"
#include "imageloader.h"
#include "sceneobjectfabric.h"
#include <iostream>

ObjectFabric<SceneImage> SceneImageFabric;

SceneImage::SceneImage()
	: SceneObject()
{}


SceneImage::~SceneImage()
{}


void SceneImage::draw ( )
{
	Video_Interface *vid=video_get_interface ( _video_name_ );
	if ( !vid ) return;
	vid->_add_sprite ( _object_name_, _scene_name_ );
}
bool SceneImage::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+="image->";
	Config_Interface *intf = config_get_interface ( storage_name );
	if ( !intf ) 
	{
		_set_error("Can't get config interface:"+config_error());
		return false;
	}		
	std::string filename=intf->_get_value ( storage_prefix+"image_file", "" );
	std::string loader=intf->_get_value ( storage_prefix+"loader", "" );
	Video_Interface *vid=video_get_interface ( _video_name_ );
	if ( !vid )
	{
		_set_error("Can't get video interface:"+video_error());
		return false;
	}
	bool load_state;
	if(loader=="")
		load_state=imageloader_loadimage_noext ( _video_name_, filename, _scene_name_, _object_name_, true );
	else 
		load_state=imageloader_loadimage ( loader,_video_name_, filename, _scene_name_, _object_name_, true );
	if ( !load_state ) 
	{
		_set_error("Can't load image:"+imageloader_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;
	}
	double xb, yb;
	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;
}
