poll_menu = CreateMenu("Poll mod")
function poll_menu:getcustombutton(b,id,def)
	if b > 0 then
		if b == 1 then
			return "(Question: "..current_poll.q
		else
			return current_poll.b[b-1]
		end
	end
end

function poll_menu:click(id,b,p)
	if b > 1 then
		USERTEMP[id]["poll_answer"] = b-1
		msgc(player(id,"name").." voted "..current_poll.b[b-1], 255, 255, 255)
	end
end

function CreatePoll(secs,quest,opt)
	if not current_poll then
		current_poll = {finish = Millisecs() + secs*1000,q = quest}
		if type(opt) == "string" then
			current_poll.b = opt:split(",")
		elseif type(opt) == "table" then
			current_poll.b = opt
		end
		poll_menu:OpenPlayer(0, 1)
		return current_poll
	end
	return nil, "There is already a poll"
end

function GetPollAnswer()
	if not current_poll then return nil end
	local answer_votes = {}
	for _, id in pairs(player(0,"table")) do
		local vote = USERTEMP[id]["poll_answer"]
		if vote then
			answer_votes[vote] = (answer_votes[vote] or 0) + 1
		end
	end
	
	return table.max(answer_votes)
end

pollmod_hud = GenerateHud()
pollmod_answer_hud = GenerateHud()

addhook("second","pollmod_sec")
function pollmod_sec()
	if current_poll then
		local votes, answer_id = GetPollAnswer()
		local answer = current_poll.b[answer_id]
		if current_poll.finish - Millisecs() <= 0 then
			if answer and votes then
				msgc("Poll: "..current_poll.q, 0, 255)
				msgc("Answer: "..answer.." votes: "..votes, 0, 255)
				
				current_poll.final_answer = answer_id
				current_poll.final_votes = votes
			else
				msgc("The poll didn't have any answer", 255)
			end
			
			Freehud(0, pollmod_hud)
			Freehud(0, pollmod_answer_hud)
			current_poll.finished = true
			current_poll = nil
			
			for i = 1, tonumber(game("sv_maxplayers")) do
				USERTEMP[i]["poll_answer"] = nil
			end
		else
			Hudtxt(pollmod_hud, "Poll: "..current_poll.q.." ("..math.floor((current_poll.finish - Millisecs())/1000)..")", 15, 160, 0, 255, 255)
			if answer and votes then
				Hudtxt(pollmod_answer_hud, "Answer: "..answer.." ("..votes.." votes)", 15, 175, 0, 255, 255)
			else
				Freehud(0, pollmod_answer_hud)
			end
		end
	else
		Freehud(0, pollmod_hud)
		Freehud(0, pollmod_answer_hud)
	end
end