#include <ZUtil/ZIniWriter.hpp>

#include <ZSTL/ZString.hpp>

/*************************************************************************/

const ZString& ZIniWriter::GetErrorString()
{
	return ErrorMessage;
}

/*************************************************************************/

bool ZIniWriter::Write( const ZKVTree& _kvtree, ZString& _output )
{
	ErrorMessage.Clear();

	ZKVTree::Iterator itr = _kvtree.Begin();
	
	if (itr == _kvtree.End())
	{
		ErrorMessage = "ZIniWriter: KV Tree has no data!";
		return false;
	}
	
	//Each node name at this level is a section
	for (size_t i = 0; i < itr.GetSiblingCount(); i++)
	{
		//Append the name in [Section] form
		_output.PushBack('[');

		ZStringAlgo::Append(_output, itr.GetName());
		
		_output.PushBack(']');

		ZStringAlgo::Append(_output, LINE_TERMINATOR);

		//Iterate the kids (the kids!)
		if (itr.CheckChild())
		{
			itr.Child();

			//Each node at this level is a key/value pair
			for (size_t j = 0; j < itr.GetSiblingCount(); j++)
			{
				//Append the kid in key=value form
				ZStringAlgo::Append(_output, itr.GetName());
				
				_output.PushBack('=');

				ZStringAlgo::Append(_output, itr.GetValue());
				ZStringAlgo::Append(_output, LINE_TERMINATOR);

				if (itr.CheckNextSibling())
					itr.NextSibling();
			}

			itr.Parent();
		}

		ZStringAlgo::Append(_output, LINE_TERMINATOR);

		if (itr.CheckNextSibling())
			itr.NextSibling();
	}

	return true;
}
