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


		#include "ui/ui_item.h"
		#include "math/vector_nml.h"
		#include "log/log.h"

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


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

	Reset();

	NMLTagForeach(pt, tag)
	{
				if	(pt->name == "Uid")
				uid = pt->GetUnsigned();
		else	if	(pt->name == "Name")
				name = pt->GetString();

		else	if	(pt->name == "Active")
				item_flags |= Flag_ItemActive;

		else	if	(pt->name == "Position")
				tVectorFromMetaTag(position, *pt);
		else	if	(pt->name == "Size")
		{
			Vector2 v;
			tVectorFromMetaTag(v, *pt);
			SetSize(v.x, v.y);
		}
		else	if	(pt->name == "Pivot")
				tVectorFromMetaTag(pivot, *pt);
		else	if	(pt->name == "Scale")
				tVectorFromMetaTag(scale, *pt);
		else	if	(pt->name == "Angle")
				angle = pt->GetReal();
		else	if	(pt->name == "ZOrder")
				zorder = pt->GetReal();

		else	if	(pt->name == "ScriptedObject")
		{
			if	(scripted_object)
				scripted_object->FromMetaTag(*pt);
		}
		else	__LOG_W__ << "Unknown tag '" << pt->name << "' in <Item2d>.\n";
	}
	return true;
}
//------------------------------------------------------------------------------

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

	root->AddChild("Name", name.toUtf8());
	root->AddChild("Uid", GetUid());

	if	(item_flags.IsSet(Flag_ItemActive))
		root->AddChild("Active");

	root->AddChild(tVectorAsMetaTag(position, "Position"));
	root->AddChild(tVectorAsMetaTag(size, "Size"));

	if	((pivot.x != 0) || (pivot.y != 0))
		root->AddChild(tVectorAsMetaTag(pivot, "Pivot"));
	if	((scale.x != 1) || (scale.y != 1))
		root->AddChild(tVectorAsMetaTag(scale, "Scale"));

	if	(GetZOrder() != 0.5)
		root->AddChild("ZOrder", GetZOrder());
	if	(GetRotation() != 0)
		root->AddChild("Angle", angle);

	// Components.
	if	(scripted_object.IsValid())
		root->AddChild(scripted_object->AsMetaTag());

	return root;
}
//------------------------------------------------------------------------------
