

multiplayer = { }


function multiplayer:init( )

end

function multiplayer:lobbyInit( )
	self._teamToPlayer = {} -- basically, calls player1 or 2 based on turn
	self._teamToPlayer[1] = player1
	self._teamToPlayer[2] = player2
	print("INIT THE SAVAGERY!")
	self._srvYouGottaKeepOnLooping = false
	self._isHost = false
	self._isClient = false

	self._player = 1

	self._serverIp = "127.0.0.1"
	self._port = 1337
	self._isHosting = nil

	self._nrConnection = 0
	Game.isMultiplayer = true
end

function multiplayer:createServer( )
	mServer:initServer(self._serverIp, self._port )
	self._srvYouGottaKeepOnLooping = true
	self._isHosting = true
	interface:setStatusLabel("Hosting")
	--mServer:closeServer( )
end

function multiplayer:joinServer(_ip, _port)
	if _ip ~= nil then
		self._serverIp = _ip
		self._port = _port
	end

	--if self._isHosting == nil then
		mClient:init( )
		mClient:connectTo(self._serverIp, self._port)
		self._srvYouGottaKeepOnLooping = true
		self._isHosting = false
		interface:setStatusLabel("Joining")
	--end
end

-- Acting as a server! Loop for server lobby
function multiplayer:handleLobbyServerLoop( )
	if self._srvYouGottaKeepOnLooping == true then

		local nrConnections = mServer:returnNrOfClients( )
		interface:setStatusLabel("Nr Con: "..nrConnections.."")

		local client = mServer:acceptCon( )
		if client ~= nil then
			interface:setStatusLabel("Listening + mr con: "..nrConnections.."")
			mServer:newClient(client, 0)
		end

		self:listenForEventsFromClient( )
	end
end




-- Acting as client! Loop for client thingies
function multiplayer:handleLobbyClientLoop( )
	if mClient:isConnected( ) == true then
		interface:setStatusLabel("Connected")
	else
		interface:setStatusLabel("Not Connected")
	end

	self:listenForEventsFroMServer()
end

function multiplayer:listenForEventsFroMServer( )
	s, status, partial = mClient:listen()

	-- check if the message received is an EventTable
	if type(s) == "string" then



		local message = string.sub(s, 1, 6)
		
		if message == "return" then -- So it's a event Table 
			self:clientParseEvents(s)

		else -- handle it as a pingTimeOut
			mClient:listenForTimeoutPings( )
		end

	end
end

function multiplayer:listenForEventsFromClient( )
	for i,v in ipairs(mServer:getClientList( ) ) do
		s, status = mServer:clientListen(v.client)
		-- check if the message received is an EventTable
		if type(s) == "string" then
			print("STRING EVENT, STRING EVENT")


			local message = string.sub(s, 1, 6)

			if message == "return" then
				self:serverParseEvents(s)
			end
		end
	end
end

function multiplayer:clientParseEvents(_event)
	local event = loadstring(_event)()
	print("EVENT TYPE FUCKING IS: "..type(event).."")

	if event._type == "ChangeMapSelection" then
		self:handleMapSelectionChanged(event._value)
	elseif event._type == "StartGameMap" then
		self:clientStartGame(event._value)
	elseif event._type == "EndTurn" then
		self:handleEndTurnEvent( )
	elseif event._type == "CreateUnit" then
		self:handleCreateUnitEvent(event)
	elseif event._type == "MoveUnit" then
		self:handleMoveUnitEvent(event)
	elseif event._type == "DamageUnit" then
		self:handleDamageReceivedEvent(event)
	end
end

function multiplayer:serverParseEvents(_event)
	local event = loadstring(_event)()

	if event._type == "EndTurn" then
		self:handleEndTurnEvent( )
	elseif event._type == "CreateUnit" then
		self:handleCreateUnitEvent(event)
	elseif event._type == "MoveUnit" then
		self:handleMoveUnitEvent(event)
	elseif event._type == "DamageUnit" then
		self:handleDamageReceivedEvent(event)
	end
end

function multiplayer:returnConnectionType( )
	return self._isHosting
end




function multiplayer:lobbyLoop( )
	
	if self._isHosting ~= nil then
		if self._isHosting == true then
			self._player = 1
			-- handle server loop
			mServer:checkTimeout( )
			self:handleLobbyServerLoop( )
		else
			-- handle client loop
			self._player = 2
			self:handleLobbyClientLoop( )

		end	
	end
end

-- event handling
--multiplayer:sendEventCreateUnit

function multiplayer:handleMapSelectionChanged(_value)
	interface:_setLobbyMapListSelection(_value)
end


function multiplayer:serverStartGame(_mapName)
	Game.mapFile = "".._mapName..""
	Game.player1 = "Human"
	player1.name = "Human"
	Game.player2 = "Computer"
	player2.name = "Computer"			
	interface:_setUpdateState(2)
	_bGuiLoaded = false
	_bGameLoaded = false
	Game:dropUI(g, resources )
	Game.lastState = 12
	currentState = 13
			
end

function multiplayer:clientStartGame(_event)
		Game.mapFile = _event
		Game.player1 = "Computer"
		player1.name = "Computer"
		Game.player2 = "Human"
		player2.name = "Human"		
		
		interface:_setUpdateState(2)
		_bGuiLoaded = false
		_bGameLoaded = false
		Game:dropUI(g, resources )
		Game.lastState = 12
		currentState = 13	
end

function multiplayer:handleEndTurnEvent( )
	unit:advanceTurn( )
end

function multiplayer:handleCreateUnitEvent(_event)
	local event = _event
	local turn = unit:_returnTurn( )
	print("EVENIMENTULLL IS: "..type(event).."")

	--local event = loadstring(_event)()
	 unit:new(event._team, event._x, event._y, event._tp)

	 local _player = self._teamToPlayer[turn]
	 _player.coins = _player.coins - _event._gold

end

function multiplayer:serverSendGoldStatus(_event)

end

function multiplayer:handleMoveUnitEvent(_event)
	local event = _event

	local v = unit:_returnTable()[event._id]
	v.goal_x = event._ex
	v.goal_y = event._ey
	v.path, v.length = pather:getPath(v.x, v.y, v.goal_x, v.goal_y)
	v.issuedOrder = true
	v.moveTimer = Game.worldTimer
	v.isThere = false
	v.objectiveSet = true	
end

function multiplayer:handleDamageReceivedEvent(_event)
	local event = _event
	local v = unit:_returnTable()[event._id1]
	local t = unit:_returnTable()[event._id2]
	unit:_do_attack(v, t)

end