round_delay = 12
votable_maps = {"de_dust","de_aztec","de_cs2d"}

CreateChat "!votemap" "" (0) [[
	votemap_menu:OpenPlayer(id, 1)
]]

nextmap_round_count = round_delay
votemap_hud = GenerateHud()

votemap_menu = CreateMenu("Vote map", table.merge(votable_maps, ","))
function votemap_menu:click(id,b,p)
	if b > 0 then
		USERTEMP[id]["mapvote"] = votable_maps[b]
		msgc(player(id,"name").." voted for map "..votable_maps[b], 0, 255)
		DrawMapVotes()
	end
end

function votemap_menu:getcustombutton(b,id,d)
	if map("name") == votable_maps[b] then
		return "("..d
	end
end
AddMenu(votemap_menu, 0)

addhook("startround","ReloadNextMap")
function ReloadNextMap()
	nextmap_round_count = nextmap_round_count - 1
	if nextmap_round_count <= 0 then
		local map_votes = {}
		for _, id in pairs(player(0,"table")) do
			local vote = USERTEMP[id]["mapvote"]
			if vote then
				map_votes[vote] = (map_votes[vote] or 0) + 1
			end
		end
		
		local votes, voted_map = table.max(map_votes)
		if voted_map then
			parse("changemap "..voted_map)
		end
	end
end

addhook("second","DrawMapVotes")
function DrawMapVotes()
	local map_votes = {}
	for _, id in pairs(player(0,"table")) do
		local vote = USERTEMP[id]["mapvote"]
		if vote then
			map_votes[vote] = (map_votes[vote] or 0) + 1
		end
	end
	
	local votes, voted_map = table.max(map_votes)
	if votes and voted_map then
		Hudtxt(votemap_hud, "Next map "..voted_map.." ("..votes.." votes) in "..nextmap_round_count.." rounds", 15, 145, 0, 255, 255)
	else
		Freehud(votemap_hud)
	end
end