MenuState = inherited("MenuState", State)

function MenuState:new()
	local o = instance(self)
	return o
end

function MenuState:init()
	self.list = GameList:new(APP.gameString, APP.versionString, _config.listHost, _config.listPath, _config.listPort, _config.token)
	self.lan = Network:new(APP.gameString, APP.versionString)
	self.lan:seek(_config.port)
	self.selectedIndex = 1
	self.time = 0
end

function MenuState:update(time)
	if self.lobby then
		self.lobby:update(time)	
	else
		self.list:update(time)
		self.lan:update(time)
		
		if self.list:isListUpdated() or self.lan:isLanListUpdated() then
			local list = {}
			local netList = self.list:getList()
	 		local lanList = self.lan:getLanHosts()
	 		if netList then
		 		for index, game in ipairs(netList) do
		 			table.insert(list, game)
		 		end
		 	end
		 	if lanList then
		 		for index, game in ipairs(lanList) do
		 			table.insert(list, game)
		 		end
	 		end
	 		self.games = list
		end
	end
	self.time = self.time + time
end

local names = {
	"Goose",
	"Iceman",
	"Maverick",
	"Sundown",
	"Merlin",
	"Skinner",
	"Chappy",
	"Pyrex",
	"Red Fox",
	"Fir",
	"Slamma",

}

function MenuState:getNick()
	if not self.nick then
		if _config.nick then
			self.nick = _config.nick
		else
			self.nick = names[math.random(1,#names)]
		end
	end
	return self.nick
end

function MenuState:keyPressed(key)
	if self.lobby then
		
	elseif self.games then
		if key == 38 then
			self.selectedIndex = math.max(1,self.selectedIndex-1)
		end
		if key == 40 then
			self.selectedIndex = math.min(#self.games,self.selectedIndex+1)
		end
	end
	if not self.lobby then
	
		if key == 72 then
			self.lobby = GameLobby:newHost(APP.gameString, APP.versionString, _config.port, _config.maxPlayers)
			self.lobby:setCallback(self)

			self.lobby:setCreator(self:getNick())
			self.lobby:setNick(self:getNick())
			self.lobby:setMap((_config.mapWidth or 100000).."x"..(_config.mapHeight or 25000)..":"..(_config.mapSeed or os.time()))
			self.lobby:setDescription(_config.description)
			
			if self.list then
				self.list:registerLobby(self.lobby)
			end
		end
		if key == 13 and self.games then
			local game = self.games[self.selectedIndex]
			if game then
				self.lobby = GameLobby:newClient(APP.gameString, APP.versionString, game.ip, game.port)
				self.lobby:setCallback(self)
				self.lobby:setCreator(game.creator)
				self.lobby:setNick(self:getNick())
				self.lobby:setMap(game.map)
				self.lobby:setDescription(game.description)
				self.lobby:setMaxPlayers(game.maxPlayers)
			end
		end
	end
	
	if self.lobby then
		if key == 83 then
			self.lobby:start()
		end
	end
end

function MenuState:onLobbyClosed()
	self.list:removeListed(self.lobby:getIp(), self.lobby:getPort())
	self.lan:removeListed(self.lobby:getIp(), self.lobby:getPort())
	self.lobby = nil
	self.list:fetch()
end

function MenuState:onLaunchHost(port, map, totalPlayers)
	local device = self.lobby.network.device
	self.lobby:disconnect()
	self.list:unregister()
	states.add(GameState:new(), "game")
	if not states.get("game"):startHost(port, totalPlayers, self:getNick()) then
	 	states.get("game").sync:replaceDevice(device)
	 	self:onError("REPLACING DEVICE WORKAROUND")
	end
	states.get("game"):setMap(map)
	states.destroy("menu")
end

function MenuState:onLaunchClient(ip, port, map, totalPlayers)
	self.lobby:disconnect()
	states.destroy("menu")
	states.add(GameState:new(), "game")
	states.get("game"):startClient(ip, port, self:getNick())
	states.destroy("menu")
end

function MenuState:renderGameListItem(game, x,y, index)
	if index == self.selectedIndex then
		video.renderRectangle(x,y-4,window.w-x*2, 40+8, 32, 255,255,255)
	end
	video.renderTextSprites(game.description, x + (game.lan and 50 or 0),y, 0, "medium", 255, 255,255,255)
	if game.lan then
		video.renderTextSprites("LAN", x,y, 0, "medium", 255, 255,128,128)
	end
	video.renderTextSprites("by "..game.creator, x,y+22, 0, "small", 255, 128,128,128)
	video.renderTextSprites(game.players.."/"..game.maxPlayers, x+200,y+22, 0, "small", 255, 128,192,128)
	video.renderTextSprites(game.map, x+300,y+22, 0, "small", 255, 255,255,128) 			
	video.renderTextSprites(algo.getSignificantTime(game.age)..algo.getSignificantTimeType(game.age).. " ago", x+520,y+22, 0, "small", 255, 255,128,255)
	return 40
end

function MenuState:getListRows()
	
end

function MenuState:render()
	if not self.lobby and (not self.games or #self.games <= 0) then
		video.renderSpriteState(SPRITES.logo, canvas.w*0.5, canvas.h*0.5, 1, 0, 255, 255, 255, 255)
	else
		video.renderSpriteState(SPRITES.logo, canvas.w*0.5, canvas.h*0.5, 1, 0, 64, 255, 255, 255)
	end
	if self.lobby then
		local x,y = canvas.w*0.5,20
		video.renderTextSprites(self.lobby:getDescription(), x,y, 1, "big", 255, 255,255,255)
		video.renderTextSprites(self.lobby:getNumberOfPlayers().."/"..self.lobby:getMaxPlayers(), canvas.w*0.9,y, 2, "medium", 255, 128,192,128)
		video.renderTextSprites("creator: "..self.lobby:getCreator(), canvas.w*0.05,y, 0, "medium", 255, 128,128,128)
		video.renderTextSprites("map:"..self.lobby:getMap(), x,y+50, 1, "big", 255, 255,255,128) 			
		local playerList = self.lobby:getPlayerList()
		if playerList then
			local x,y = canvas.w*0.5, 200
			for index, player in ipairs(playerList) do
				local a = 255
				if player.blinkTimer then
					a = a - math.max(0,math.sign(math.cos(player.blinkTimer*math.pi*4)))*125
				end
				if self.lobby:isLocalPlayer(player) then
					video.renderTextSprites(player.nick, x,y, 1, "medium", a, 192,255,192)	
				else
					video.renderTextSprites(player.nick, x,y, 1, "medium", a, 128,255,128)
				end
				y = y +30
			end
		end
		if self.lobby.network:getGuid() then
			video.renderTextSprites("guid:"..self.lobby.network:getGuid(), canvas.w*0.05,y+30, 0, "small", 64, 255,255,128) 			
		end
		
		if self.lobby:isStarting() then
			video.renderRectangle(0,0,canvas.w, canvas.h, 128, 0,0,0)
			video.renderTextSprites("STARTING!", canvas.w*0.5,canvas.h*0.5+fonts.alignY("big"), 1, "big", 255, 64,255,64)
			video.renderTextSprites(math.floor(self.lobby:getStartDelay()), canvas.w*0.5,canvas.h*0.5+fonts.alignY("big")+50, 1, "big", 255, 255,255,64)
		end

		video.renderTextSprites("S to start", canvas.w*0.5, canvas.h- 175,1, "big", 255,255,255,255)
	elseif self.games then
	 	local x,y = 100, 20
 		for index, game in ipairs(self.games) do
 			y = y + self:renderGameListItem(game, x,y, index)
 		end
 		video.renderTextSprites("H to host", canvas.w*0.5, canvas.h- 175, 1, "big", 255,255,255,255)
	end

	video.renderTextSprites("check www.oxeyegames.com for possible updates!", canvas.w*0.5, canvas.h- 100, 1, "medium", 255,128,128,128)

	video.renderTextSprites("version: "..APP.versionString , canvas.w*0.5, canvas.h- 55, 1, "medium", 255,80,120,80)

	--for i=1,20 do
	--	video.renderLine(10, 100, 2000, 100, 255, 255, 255, 255)
	--	video.renderLine(10, 100, 10, 2000, 255, 255, 255, 255)
	-- 	video.renderScaledSpriteState(SHIP_TYPES[1].sprites.wingTop, 10 + i*70, 100, 1, -1 + 2*i/20, 1, self.time*0.1, 255,255,255,255)
	-- 	video.renderScaledSpriteState(SHIP_TYPES[1].sprites.wingTop, 10 + i*70, 200, 1, i/20, 1, -math.pi*0.1, 255,255,255,255)
	-- 	video.renderScaledSpriteState(SHIP_TYPES[1].sprites.wingTop, 10 + i*70, 300, 1, i/20, 1, -math.pi*0.2, 255,255,255,255)
	-- 	video.renderScaledSpriteState(SHIP_TYPES[1].sprites.wingTop, 10 + i*70, 400, 1, i/20, 1, -math.pi*0.3, 255,255,255,255)
--
	-- 	video.renderScaledSpriteState(SHIP_TYPES[1].sprites.wingTop, 50 , 500, 1, 1, 1, self.time*0.1/math.pi*i, 255,255,255,255)
	--end
end

function MenuState:close()
	--self.list:unregister()
end
