#include "pw/scripting/script.hpp"

#include "pw/scripting/scripting.hpp"

#include "pw/scene/node.hpp"

#include "script_core.hpp"
#include "script_system.hpp"
#include "script_scene.hpp"

namespace pw {

struct lua_state : public script::state {

	scripting::state _state;
	scripting::table _namespace;

	void load_modules();

	lua_state() {

		// create global pw namespace
		_namespace = _state.create_named_table("pw");

		// add the script as a user type
		_namespace.new_usertype<lua_state>("script",
										   "initialize",&lua_state::load_modules
										   );

		// add this instance as "script"
		_namespace.set("script",this);
	}

	virtual int run(const std::string &s);

};

int lua_state::run(const std::string &s)
{
	return _state.script(s.c_str()).get<int>();
}

void lua_state::load_modules() {

	// open all libraries
	_state.open_libraries();

	script_core::load(_namespace);
	script_system::load(_namespace);
	script_scene::load(_namespace);

}


script::script()
{
	_state.reset(new lua_state());
}

script::~script()
{
	_state = nullptr;
}

int script::run(const std::string &s)
{
	return _state->run(s);

}


}




