#include "main.h"
#include <lua.h>
#include <lauxlib.h>
#include "lua_main.h"

static int lib_send(lua_State *L)
{
	// send a message to the client / server
	bool client = lua_toboolean(L,lua_upvalueindex(1));
	if (client) {
		size_t len;
		const char *msg = luaL_checklstring(L,1,&len);
		if (!len)
			return 0;
		// If offline:
		Lua_NetRecv(0,msg,len); // Server recieves from client 0 instantly
	}
	else {
		size_t len;
		Uint32 dest = luaL_checkinteger(L,1);
		const char *msg = luaL_checklstring(L,2,&len);
		if (!len)
			return 0;
		// If offline:
		if (dest != 0)
			return 0; // Cannot send to imaginary players
		Lua_NetRecv(-1,msg,len); // Client recieves from server instantly
	}
	return 0;
}

void agllib_net(lua_State *L, bool client)
{
	lua_newtable(L);
#ifdef DEDICATED
	lua_pushboolean(L,false); // always false for dedicated servers
#else
	lua_pushboolean(L,true); // true if you are playing offline, false if connected to a network or hosting
#endif
	lua_setfield(L,-2,"offline");
	lua_pushboolean(L,client);
	lua_pushcclosure(L,lib_send,1);
	lua_setfield(L,-2,"send");
	lua_setglobal(L,"net");

	lua_newtable(L);
	lua_pushinteger(L,1);
	lua_setfield(L,-2,"GUARANTEED");
	lua_pushinteger(L,1<<1);
	lua_setfield(L,-2,"ORDERED");
	lua_setglobal(L,"NET");
}
