Middleman = {};

require("middleman/host");
require("middleman/client");

Middleman.Middleman = class.new();

function Middleman.Middleman:constructor(localPort, destHost, destPort, tcpOrUdp)
	self.host	=	Middleman.Host(localPort, tcpOrUdp);
	self.client	=	Middleman.Client(destHost, destPort, tcpOrUdp);
end

function Middleman.Middleman:handleEvents(e, ...)
	local handleCallbacks = {
		'socketconnected',
		'socketdisconnected',
		'socketreceived',
		'socketerror',
	};

	if( table.find(handleCallbacks, e) ) then
		--print(sprintf("\tTO(%s)->", e), ...);

		-- Since we are calling this manually, we need to also
		-- pass 'self' as the first argument to preserve the pointer
		Middleman.Middleman[e](self, ...);
	end
end

function Middleman.Middleman:socketconnected(clientsock, listenSockId)
	if( listenSockId ~= self.host.socket:id() ) then
		return false;
	end

	printf("[Middleman] Socket %d connected\n", clientsock:id());

	self.host:addClient(clientsock:id());
	return true;
end

function Middleman.Middleman:socketdisconnected(socketId)
	if( not self.host:hasClient(socketId) ) then
		return false;
	end

	printf("[Middleman] Socket %d disconnected\n", socketId);
	self.host:removeClient(socketId);
	return true;
end

function Middleman.Middleman:socketreceived(socketId, dataReceived)
	if( not self.host:hasClient(socketId) ) then
		return false;
	end

	print("[Middleman] Received on socket", socketId, "this value:", dataReceived);

	for i = 1,#dataReceived do
		local extra = "";
		if( i < #dataReceived ) then extra = " "; else extra = "\n"; end;

		local bytes = string.byte(dataReceived, i, i);
		printf("0x%X%s", bytes, extra);
	end

	self.client:send(dataReceived);
end