#pragma once

#include "luax/impl/luareturn.h"
#include "luax/impl/luatype.h"
#include <lualib.h>

namespace Luax
{

	struct LuaGlobal
	{
		LuaGlobal(lua_State* lstate, const char* name, void* val)
			: mLstate(lstate)
			, mName(name)
		{
			lua_pushlightuserdata(lstate, val);
			lua_setglobal(lstate, name);
		}

		~LuaGlobal()
		{
			if (mLstate)
			{
				lua_pushnil(mLstate);
				lua_setglobal(mLstate, mName);
			}
		}

		LuaGlobal(LuaGlobal&& b)
			: mLstate(b.mLstate)
			, mName(b.mName)
		{
			b.mLstate = nullptr;
		}

		LuaGlobal(const LuaGlobal&) = delete;
		LuaGlobal& operator=(const LuaGlobal&) = delete;

		lua_State* mLstate = nullptr;
		const char* mName = nullptr;
	};

	inline LuaReturn GetLuaGlobal(lua_State* lstate, const char* name)
	{
		lua_getglobal(lstate, name);
		if (lua_isnil(lstate, -1))
		{
			return { nullptr };
		}
		return { lstate, -1 };
	}

	template<typename T>
	inline void SetLuaGlobal(lua_State* lstate, const char* name, T val)
	{
		PushReturnToLua(lstate, val);
		lua_setglobal(lstate, name);
	}

}