// ---------------------------------------------------------------------------
// 
//   Lily Engine alpha
// 
//   Copyright (c) 2010 Clifford Jolly
//     http://cliffjolly.com
//     cliff@cliffjolly.com
// 
// ---------------------------------------------------------------------------
// 
//   This program is free software; you can redistribute it and/or modify
//   it under the terms of the GNU General Public License as published by
//   the Free Software Foundation; either version 2 of the License, or
//   (at your option) any later version.
//  
//   This program is distributed in the hope that it will be useful, but
//   WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
//   General Public License for more details.
// 
//   You should have received a copy of the GNU General Public License
//   along with this program; if not, write to the Free Software
//   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
//   USA
// -------------------------- END HEADER -------------------------------------

#pragma once

#include <string>
#include <map>

#include "../3rdparty/tinyxml/tinyxml.h"

extern "C" {
#include "lua.h"
#include "lualib.h"
#include "lauxlib.h"
}

/** @brief Class to handle saving and loading of Lua data.*/
class LuaTableSerializer {
	public:
		/** @brief Create a Lua table from an XML node and push it onto the stack.
				Recreates all the tables and data referred to directly or
				indirectly from this table.
			@param L Pointer to the lua_State.
			@param luaStateXml Pointer to the TiXmlElement with the root table node.
		*/
		void tableFromXml(lua_State *L, TiXmlElement *luaStateXml);
	
		/** @brief Creates an XML tree from the table at the top of the stack.
				Also any tables that are referred to directly or indirectly
				from it.
			@param L Pointer to the lua_State.
			@return A TiXmlElement with the tree (dynamically allocated - must be freed separately).
		*/
		TiXmlElement *tableToXml(lua_State *L);
		
	private:
		std::map<const void*, int> referenceIndices;
		int refTableStackPos;
		
		// Push a value onto the stack from a val/key element.
		void pushVal(lua_State *L, TiXmlElement *e);
	
		// For reference generation. Just checks the top of the stack to see
		// if it's a table and, if so, saves a reference and recurses.
		void checkStackTop(lua_State *L);
		
		// Recursively generate references.
		void genReferences(lua_State *L);
	
};

/** @brief Find a global name that refers to the same table as the
 * __index inside the metatable for the table on the top of the Lua
 * stack.
 * @param L The lua_State.
 * @return The global name, or a zero-length string if it found nothing.
 * */
std::string findGlobalNameForMetaTable(lua_State *L);
