-- Client network messages
net.recv = {}

function GAME:NetRecv(msg)
	local id = msg:bin(1)
	if net.recv[id]
		net.recv[id](msg:sub(2))
	else
		console.print("WARNING: Unhandled message type "..(NETMSG[id] or id).." recieved!")
	end
end

net.recv[NETMSG.CHAT] = function(msg)
	console.print(msg)
end

net.recv[NETMSG.MAP] = function(msg)
	tsc.reset()
	stage.load(msg)
	title.reset()
end

net.recv[NETMSG.TITLE] = function(msg)
	title.mode(true)
end

net.recv[NETMSG.ENT_SPAWN] = function(msg)
	if not stage.loaded return end
	local e = {
		id = msg:bin(1),
		type = msg:bin(2,2),
		x = msg:bin(4,4),
		y = msg:bin(8,4),
		flags = msg:bin(12,4),
		anim = msg:bin(16)
	}
	--console.debug("Spawning ent "..e.id..": "..e.type)
	NPC.spawn(e)
end

net.recv[NETMSG.ENT_ANIM] = function(msg)
	if not stage.loaded return end
	local id = msg:bin(1)
	local ent = stage.ents[id]
	if not ent return end
	ent.x = msg:bin(2,4)
	ent.y = msg:bin(6,4)
	local last_anim = ent.anim
	ent.anim = msg:bin(10,1)
	if anim ~= last_anim
		ent.frame = 1
		ent.ticks = 0
	end
	ent.flip = msg:bin(11,1) ~= 0
	ent.flags = ent.flags & (~NPCF.FLIP)
	if ent.flip
		ent.flags = ent.flags | NPCF.FLIP
	end
end

net.recv[NETMSG.ENT_MOVE] = function(msg)
	if not stage.loaded return end
	local id = msg:bin(1)
	local ent = stage.ents[id]
	if not ent return end
	ent.x = msg:bin(2,4)
	ent.y = msg:bin(6,4)
	ent.mx = msg:bin(10,1)
	ent.my = msg:bin(11,1)
	ent.anim = msg:bin(12,1)
end

net.recv[NETMSG.TSC_MSG] = function(msg)
	tsc.msgbox = msg:bin(1)
	if tsc.msgbox == 0 -- <CLO
		tsc.msgbox = nil
		tsc.msgtext = {}
	end
end

net.recv[NETMSG.TSC_TEXT] = function(msg)
	local tur = msg:bin(1)
	msg = msg:sub(2)
	if tur == 0
		tsc.tur = false
		tsc.addtext = {0,msg,0}
	else
		tsc.tur = true
		local p = 1
		while p <= #msg
			local char = msg:sub(p,p)
			if char == '\n'
				table.insert(tsc.msgtext,1,"")
				tsc.msgtext[4] = nil
			else
				tsc.msgtext[1] = (tsc.msgtext[1] or "") .. char
			end
			p = p + 1
		end
	end
end

net.recv[NETMSG.TSC_NOD] = function(msg)
	tsc.nod = true
end

net.recv[NETMSG.TSC_CLR] = function(msg)
	tsc.msgtext = {}
end

net.recv[NETMSG.TSC_END] = function(msg)
	tsc.reset()
end

net.recv[NETMSG.TSC_FAI] = function(msg)
	fade.time = 0
	fade.dir = msg:bin(1)
	fade.move = true
end

net.recv[NETMSG.TSC_FAO] = function(msg)
	fade.time = 0
	fade.dir = msg:bin(1)
	fade.move = false
end

function net.send_chat(text)
	net.send(string.num(NETMSG.CHAT) .. text)
end

function net.send_title(menu)
	net.send(string.num(NETMSG.TITLE) .. string.num(menu),NET.GUARANTEED)
end

function net.tsc_text()
	net.send(string.num(NETMSG.TSC_TEXT),NET.GUARANTEED)
end

function net.tsc_nod()
	net.send(string.num(NETMSG.TSC_NOD),NET.GUARANTEED)
end
