-- Server stuff.

-- Note that all of these maps can be by name if you prefer.
-- Intro and Start maps are by number for existing mod compatibility.
Intro = {
	Map = 72,
	Event = 100
}

Title = {
	Map = nil, -- For some background behind the menu
	Event = nil -- Should be an automated loop or something, will recieve no input
}

Start = {
	Map = 13,
	Pos = {10,8},
	--Event = 200,
	Event = 90,
	Health = 3
}

players = {}

function GAME:Init()
	if net.offline
		self:NetJoin(0) -- hack
	end
end

function GAME:NetJoin(uid)
	-- TODO: Assume uid 0 means offline mode?
	players[uid] = {
		id = uid,
		spawned = false,
		intro = net.offline
	}
	if players[uid].intro
		net.send_map(uid,stage.load(Intro.Map))
		net.tsc_nod(uid)
		tsc.start(players[uid],Intro.Event,true)
	else
		-- TODO: Load saved game here.
		net.send_map(v.id,stage.load(Start.Map))
		tsc.start(v,Start.Event,true)
	end
end

function GAME:NetLeave(uid)
	local stage = players[uid].stage
	if stage
		stage.players[uid] = nil
	end
	players[uid] = nil
end

function GAME:Start(player,load,clearskip)
	if clearskip or not player.skipflags
		-- This resets when first connecting (regardless of new game or loading)
		-- It doesn't reset when loading or resetting after death
		-- The purpose is to skip story events which have already been seen,
		-- i.e. dying in First Cave doesn't show Kazuma's lengthy monologue again.
		player.skipflags = {}
	end

	if load
		-- TODO: Load saved game here
	else
		-- New game stuff
		player.eventflags = {}
		player.items = {}
		player.equips = 0
		player.teleports = {}
		player.mapflags = {}

		player.health = Start.Health
		player.max_health = Start.Health
		player.flip = false
		player.skin = skins["default"]

		net.send_map(player.id,stage.load(Start.Map))
		net.spawn_client(player,Start.Pos)
		tsc.start(player,Start.Event,true)
	end
end

function GAME:Think()
	for k,v in pairs(stages)
		if not next(v.players)
			console.debug("Unloaded map "..k)
			stages[k] = nil
		else
			for k,v in pairs(v.ents)
				NPC.think(v)
			end
		end
	end
	for id,self in pairs(players)
		tsc.run(self)
		if self.intro and not self.tsc
			self.intro = nil
			net.send_title(id)
			if Title.Map
				net.send_map(id,stage.load(Title.Map))
				if Title.Event
					tsc.start(self,Title.Event,true)
				end
			else
				net.send_map(id,'0')
			end
		elseif self.spawned
			local mx,my = stage.doCollisions(self,(self.mx / 0x200),(self.my / 0x200))
			self.mx,self.my = math.floor(mx*0x200),math.floor(my*0x200)
		end
	end
end
