// **********************************************************************
//                            OpenAlchemist
//                        ---------------------
//
//  File        : FrontLayer.cpp
//  Description : 
//  Author      : Guillaume Delhumeau <guillaume.delhumeau@gmail.com>
//  License     : GNU General Public License 2 or higher
//
// **********************************************************************

#include <list>
#include <zip.h>
#include "FrontLayer.h"
#include "misc.h"
#include "memory.h"
#include "CommonResources.h"

/************************************************************************/
/* Load GFX                                                             */
/************************************************************************/
void FrontLayer::load_gfx(SDL_Renderer *gc, std::string skin)
{
	unload_gfx();

	// Look if frontlayer.xml is existing
	is_enabled = false;
	zip_file_t *f = NULL;
	if (f = zip_fopen(common_resources_get_instance()->skin_zip, "frontlayer.xml", 0))
	{
		zip_fclose(f);
		is_enabled = true;
		CL_ResourceManager gfx_frontlayer("frontlayer.xml");
		_load_gfx(gc, &gfx_frontlayer);
	}

}

/************************************************************************/
/* Load GFX                                                             */
/************************************************************************/
void FrontLayer::_load_gfx(SDL_Renderer *gc, CL_ResourceManager* p_gfx_frontlayer)
{
	unload_gfx();

	int number = CL_Integer_to_int("frontlayer/number_of_sprites", p_gfx_frontlayer);
	for(int i=1; i<=number; ++i)
	{
		FrontLayerSprite *fsprite = my_new FrontLayerSprite();
		fsprite -> _sprite = CL_Sprite(gc, "frontlayer/"+to_string(i)+"/sprite", p_gfx_frontlayer);
		fsprite -> left = CL_Integer_to_int("frontlayer/"+to_string(i)+"/left", p_gfx_frontlayer);
		fsprite -> top = CL_Integer_to_int("frontlayer/"+to_string(i)+"/top", p_gfx_frontlayer);
		list.insert(list.end(), fsprite);
	}
}

/************************************************************************/
/* Unload GFX                                                           */
/************************************************************************/
void FrontLayer::unload_gfx()
{
	std::list<FrontLayerSprite*>::iterator it = list.begin();
	while(!list.empty())
	{
		my_delete(*it);
		it = list.erase(it);
	}

	is_enabled = false;
	list.clear();
}

/************************************************************************/
/* Draw                                                                 */
/************************************************************************/
void FrontLayer::draw(SDL_Renderer *gc)
{
	std::list<FrontLayerSprite*>::iterator it = list.begin();
	while(it != list.end())
	{
		FrontLayerSprite* p_fsprite = (FrontLayerSprite*)*it;
		p_fsprite -> _sprite.draw(gc, p_fsprite -> left, p_fsprite -> top);
		p_fsprite -> _sprite.update();
		it++;
	}
}
