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


		#include "ui/ui_sprite.h"
		#include "ui/ui.h"
		#include "metafile/nml.h"
		#include "log/log.h"

		using namespace GS::S2D;
		using GS::NML::Tag;


//------------------------------------------------------------------------------
bool				Sprite::FromMetaTag(Tag &tag)
{
	if	(tag.name != "Sprite")
		__ERR__(__LOG_E__ << "Could not parse sprite, incorrect root tag (" << tag.name << ").\n", false)

	opacity = 1.f;

	// Parse root tags.
	NMLTagForeach(pt, tag)
	{
				if	(pt->name == "Item")
				Item::FromMetaTag(*pt);

		else	if	(pt->name == "Opacity")
				opacity = pt->GetReal();

		else	if	(pt->name == "Flag")
		{
			NMLTagForeach(st, *pt)
			{
						if	(st->name == "FlipU")
						sprite_flags.Raise(FlagFlipU, true);
				else	if	(st->name == "FlipV")
						sprite_flags.Raise(FlagFlipV, true);

				else	if	(st->name == "Opaque")
						sprite_flags |= FlagBlendOpaque;
				else	if	(st->name == "Additive")
						sprite_flags |= FlagBlendAdditive;

				else	if	(st->name == "NonSensitive")
						sprite_flags |= FlagNonSensitive;
				else	if	(st->name == "ResolutionInvariant")
						sprite_flags |= FlagResolutionInvariant;
				else	if	(st->name == "TransformUV")
						sprite_flags |= FlagTransformUV;
			}
		}
		else	if	(pt->name == "Texture")
			texture = pt->GetString();

		else	__LOG_W__ << "Unknown tag '" << pt->name << "' in <Sprite2d>.\n";
	}
	return true;
}
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
Tag					*Sprite::AsMetaTag() const
{
	Tag *root = new Tag("Sprite");
	if	(!root)
		__ERR__(__LOG_E__ << "Could not create root tag to serialize.\n", NULL)

	root->AddChild(Item::AsMetaTag());

	if	(opacity != 1.f)
		root->AddChild("Opacity", opacity);
	if	((type == Type_Sprite) && !texture.IsEmpty())
		root->AddChild("Texture", texture.c_str());

	if	(Tag *flag_tag = root->AddChild("Flag"))
	{
		if	(sprite_flags.IsSet(FlagFlipU))
			flag_tag->AddChild("FlipU");
		if	(sprite_flags.IsSet(FlagFlipV))
			flag_tag->AddChild("FlipV");
		if	(sprite_flags.IsSet(FlagNonSensitive))
			flag_tag->AddChild("NonSensitive");
		if	(sprite_flags.IsSet(FlagBlendAdditive))
			flag_tag->AddChild("Additive");
		if	(sprite_flags.IsSet(FlagResolutionInvariant))
			flag_tag->AddChild("ResolutionInvariant");
		if	(sprite_flags.IsSet(FlagTransformUV))
			flag_tag->AddChild("TransformUV");
	}
	return root;
}
//------------------------------------------------------------------------------
