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


		#include "data/registry.h"

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


//------------------------------------------------------------------------------
Tag				*Registry::CreateKey(const char *path, const Variant *value, bool /*recursive*/)
{
	StringList	tag_path_list;
	String(path).TrimChar(';').Split(":", tag_path_list);

	Tag *ctag = NULL;
	for (uint n = 0; n < tag_path_list.GetCount(); ++n)
	{
		String &tag_path = tag_path_list.ObjectAt(n);

		Tag *ntag = ctag ? ctag->GetTag(tag_path) : GetTag(tag_path);
		if	(ntag == NULL)
			ntag = ctag ? ctag->AddChild(tag_path) : AddRoot(tag_path);
		if	((ctag = ntag) == NULL)
			return NULL;
	}

	if	(ctag && value)
	{
		ctag->GetValue() = *value;
		RegistryKeyChange msg(path);
		BroadcastMessage(RegistryMsg_KeyChange, this, &msg);
	}
	return ctag;
}
Tag				*Registry::CreateKey(const char *path, const Variant &value, bool recursive)
{	return CreateKey(path, &value, recursive);	}
bool				Registry::DeleteKey(const char *path)
{
	StringList	tag_path_list;
	String(path).Split(":", tag_path_list);

	Tag *ctag = NULL, *ptag = NULL;
	for (uint n = 0; n < tag_path_list.GetCount(); ++n)
	{
		ptag = ctag;
		String &tag_path = tag_path_list.ObjectAt(n);
		Tag *ntag = ctag ? ctag->GetTag(tag_path) : GetTag(tag_path);
		if	(!ntag)
			return false;
		ctag = ntag;
	}
	if	(!ctag)
		return false;

	if	(ptag)
		ptag->RemoveTag(ctag);
	else
		tags.Remove(ctag);

	_safe_delete(ctag);
	return true;
}
//------------------------------------------------------------------------------

//------------------------------------------------------------------------------
float				Registry::GetReal(const char *path, float default_value) const
{
	Tag *tag = GetTag(path);
	float v;
	if	(!tag || !tag->GetValue().Get(v))
		return default_value;
	return v;
}
bool				Registry::GetBool(const char *path, bool default_value) const
{
	Tag *tag = GetTag(path);
	bool v;
	if	(!tag || !tag->GetValue().Get(v))
		return default_value;
	return v;
}
//------------------------------------------------------------------------------
