MAYOR_VOTING = {}
MAYOR_VOTING.CurrentHeight = 50

surface.CreateFont("Bebas24Font", {font = "BebasNeue", size= 24, weight = 400, antialias = true})
surface.CreateFont("Bebas40Font", {font = "BebasNeue", size= 40, weight = 400, antialias = true})
surface.CreateFont("Bebas70Font", {font = "BebasNeue", size= 70, weight = 400, antialias = true})
surface.CreateFont("OpenSans18Font", {font = "Open Sans Condensed", size= 18, weight = 400, antialias = true})

include("mayorvoting/sh_votingconfig.lua")
include("mayorvoting/panels/cl_votingpanel.lua")
include("mayorvoting/panels/cl_playericon.lua")

local VotingMainWindow
function MAYOR_VOTING.OpenVoteScreen(settings)
	MAYOR_VOTING.MainWindowOpen = true
	if !IsValid(VotingMainWindow) then
		VotingMainWindow = vgui.Create("DFrame")
		VotingMainWindow:SetSize(ScrW(), 300)
		VotingMainWindow:SetDraggable(false)
		if !MAYOR_VOTING.Settings.ShowCloseButton then
			VotingMainWindow:ShowCloseButton(false)
		else
			VotingMainWindow.Close = function()
				MAYOR_VOTING.CloseVoteScreen()
			end
		end
		VotingMainWindow:SetTitle("")
		VotingMainWindow:SetBackgroundBlur(true)
		VotingMainWindow:SetZPos(-10)
		VotingMainWindow.VoteTime = settings.time
		MAYOR_VOTING.CanCloseTime = CurTime() + settings.time
		VotingMainWindow.Paint = MAYOR_VOTING.PaintMainWindow
		MAYOR_VOTING.VoteManager = {}
		local VotingPanelsList = vgui.Create("DPanelList", VotingMainWindow)
		VotingPanelsList:SetPadding(0)
		VotingPanelsList:SetSpacing(5)
		VotingPanelsList:SetAutoSize(true)
		VotingPanelsList:SetNoSizing(false)
		VotingPanelsList:EnableHorizontal(true)
		VotingPanelsList:EnableVerticalScrollbar(false)
		VotingPanelsList.Paint = function() end
		VotingPanelsList:SetWide(ScrW() - (ScrW() / 10))
		VotingPanelsList:SetPos((ScrW() / 10) / 2, 70)
		for k,v in pairs(settings.Candidates) do
			if IsValid(v.player) then
				local VotingPanel = vgui.Create("PlayerVotingPanel")
				VotingPanel:SetPlayer(v.player)
				VotingPanel:SetColor(MAYOR_VOTING.NewVotingPanelColor())
				VotingPanel.DoClick = function()
					if LocalPlayer().HasVoted then return end
					LocalPlayer():ConCommand("mayor_vote "..k)
					local player = VotingPanel:GetPlayer()
					if IsValid(player) then
						VotingPanel:ToggleSelect(true)
						LocalPlayer().HasVoted = true
						if MAYOR_VOTING.Settings.ForceMouseCursor then
							gui.EnableScreenClicker(false)
						end
					end
				end
				table.insert(MAYOR_VOTING.VoteManager, VotingPanel)
				VotingPanelsList:AddItem(VotingPanel)
			end
		end
		local maxwidth = VotingPanelsList:GetWide()
		local curwidth  = 0
		local items = 0
		for _,v in pairs(VotingPanelsList:GetItems()) do
			curwidth = curwidth + (v.CurrentWidth) + 5
			if (curwidth > maxwidth) then
				break
			else
				items = (items + 1)
			end
		end
		VotingPanelsList:SetWide(355 * items)
		VotingPanelsList:SetPos((ScrW() - VotingPanelsList:GetWide()) / 2, 70)
		local rows = 0
		rows = math.ceil(#MAYOR_VOTING.VoteManager / items)
		MAYOR_VOTING.MaxHeight = 130 + (70 * rows)
		VotingMainWindow:SetSize(ScrW(), MAYOR_VOTING.MaxHeight)
		if MAYOR_VOTING.Settings.ForceMouseCursor then
			gui.EnableScreenClicker(true)
		end
	else
		MAYOR_VOTING.CloseVoteScreen()
	end
end

function MAYOR_VOTING.PaintMainWindow()
	surface.SetDrawColor(MAYOR_VOTING.Theme.WindowColor)
	MAYOR_VOTING.CurrentHeight = math.Approach(MAYOR_VOTING.CurrentHeight, MAYOR_VOTING.MaxHeight, FrameTime() * 400)
	surface.DrawRect(0, 0, ScrW(), MAYOR_VOTING.CurrentHeight)
	local time = math.Clamp(MAYOR_VOTING.CanCloseTime - CurTime(), 0, VotingMainWindow.VoteTime)
	local timetext = string.FormattedTime(time, "%02i:%02i")
	local text = MAYOR_VOTING.Settings.VotingTitle.." "..os.date("%Y").."  ("..timetext  ..")"
	if MAYOR_VOTING.ResultsScreen then text = MAYOR_VOTING.Settings.ResultsTitle end
	draw.DrawText(text, "Bebas40Font", (ScrW() / 2), 10, MAYOR_VOTING.Theme.TitleTextColor, TEXT_ALIGN_CENTER)
	if MAYOR_VOTING.VoteTickerAlpha > -1 then
		MAYOR_VOTING.VoteTickerAlpha = math.Clamp(MAYOR_VOTING.VoteTickerAlpha + FrameTime() * MAYOR_VOTING.NotificationDirFT * 300, 0, 190)
		local c = MAYOR_VOTING.VoteTickerColor
		local r,g,b = c.r,c.g,c.b
		local w,h = surface.GetTextSize(MAYOR_VOTING.VoteTickerMessage)
		local ypos = (ScrW() / 2) - (w / 4)
		draw.WordBox(2, ypos, (MAYOR_VOTING.MaxHeight - 30), MAYOR_VOTING.VoteTickerMessage, "OpenSans18Font", Color(r,g,b,MAYOR_VOTING.VoteTickerAlpha), color_white)
	end
end

function MAYOR_VOTING.CloseVoteScreen()
	if VotingMainWindow then
		VotingMainWindow:Remove()
		VotingMainWindow = nil
		MAYOR_VOTING.CanCloseTime = nil
		MAYOR_VOTING.LastPanelNumber = nil
		MAYOR_VOTING.VoteTickerAlpha = -1
		MAYOR_VOTING.VoteTickerMessage = "Eine Stimme wurde abgegeben."
		MAYOR_VOTING.ResultsScreen = nil
		LocalPlayer().HasVoted = nil
	end
	MAYOR_VOTING.MainWindowOpen = false
end

net.Receive("Voting_NewVote", function()
	local votedata = net.ReadTable()
	local votetime = MAYOR_VOTING.VoteTime
	local settings = {}
	settings.Candidates = votedata
	settings.time = votetime
	MAYOR_VOTING.OpenVoteScreen(settings)
	if MAYOR_VOTING.Settings.MenuSounds then
		surface.PlaySound(MAYOR_VOTING.Settings.NewVoteSound)
	end
end)

net.Receive("Voting_EndVote", function(l,c)
	if !MAYOR_VOTING.MainWindowOpen then return end
	local winningplayer = net.ReadEntity()
	if IsValid(winningplayer) and MAYOR_VOTING.VoteManager then
		MAYOR_VOTING.ResultsScreen = true
		for _,v in pairs(MAYOR_VOTING.VoteManager) do
			if v:GetPlayer() != winningplayer then
				v:SetNoActionAvailable(true)
			else
				MAYOR_VOTING.VoteTickerAlpha = 0
				MAYOR_VOTING.VoteTickerMessage = string.format("Herzlichen Glückwunsch an den Gewinner, %s!", winningplayer:Name())
				MAYOR_VOTING.VoteTickerColor = v:GetColor()
			end
		end
	end
	if MAYOR_VOTING.Settings.MenuSounds then
		surface.PlaySound(MAYOR_VOTING.Settings.VoteResultsSound)
	end
	timer.Simple(MAYOR_VOTING.Settings.CloseTimeAfterVoteEnds, MAYOR_VOTING.CloseVoteScreen)
end)

net.Receive("Voting_VoteCast", function(l,c)
	if !MAYOR_VOTING.MainWindowOpen then return end
	local candidate = net.ReadEntity()
	local player = net.ReadString()
	for _, v in pairs(MAYOR_VOTING.VoteManager) do
		if v:GetPlayer() == candidate and IsValid(candidate) then
			v:IncreaseVote(1)
			if MAYOR_VOTING.Settings.ShowVoteTickerUpdates then
				MAYOR_VOTING.VoteTickerAlpha = 0
				MAYOR_VOTING.VoteTickerMessage = string.format("%s hat für %s gestimmt", player, candidate:Name())
				MAYOR_VOTING.VoteTickerColor = v:GetColor()
			end
		end
	 end
end)

MAYOR_VOTING.VoteTickerAlpha = -1
MAYOR_VOTING.VoteTickerMessage = "Eine Stimme wurde abgegeben."
MAYOR_VOTING.VoteTickerColor = Color(26, 83, 255)
MAYOR_VOTING.NotificationDirFT = 1
MAYOR_VOTING.VotingStaticColors = {Color(26,83,255), Color(255,77,77), Color(230,184,0), Color(0,179,54)}

local ConfirmMenuVisible = false
function MAYOR_VOTING.ConfirmCandidacy()
	if ConfirmMenuVisible then return end
	ConfirmMenuVisible = true
	Derma_Query("Möchtest du dich für die nächste Bürgermeisterwahl einschreiben, "..LocalPlayer():Name().."?", "Bürgermeisterwahl "..os.date("%Y"), "Ja "..(CUR or GAMEMODE.Config.currency or "$")..tostring(string.Comma(MAYOR_VOTING.CandidateCost)), function() LocalPlayer():ConCommand("mayor_join_vote") ConfirmMenuVisible = false end, "Abbrechen", function() ConfirmMenuVisible = false end)
end
usermessage.Hook("MAYOR_VOTING_Confirm", MAYOR_VOTING.ConfirmCandidacy)

function MAYOR_VOTING.NewVotingPanelColor()
	if !MAYOR_VOTING.LastPanelNumber then
		MAYOR_VOTING.LastPanelNumber = 1 
	else
		MAYOR_VOTING.LastPanelNumber = (MAYOR_VOTING.LastPanelNumber + 1)
	end
	if MAYOR_VOTING.VotingStaticColors[MAYOR_VOTING.LastPanelNumber] then
		return MAYOR_VOTING.VotingStaticColors[MAYOR_VOTING.LastPanelNumber]
	else
		local part = math.random(1, 3)
		if part == 1 then
			return Color(255, math.random(0, 255), math.random(0, 255))
		elseif part == 2 then
			return Color(math.random(0, 255), 255, math.random(0, 255))
		else
			return Color(math.random(0, 255), math.random(0, 255), 255)
		end
	end
end

local function MayorVotingChatNotice(msg)
	local text = msg:ReadString() or "Keine Nachricht.."
	chat.AddText(MAYOR_VOTING.Theme.NoticeTextColor, text)
end
usermessage.Hook("Voting_ChatNotice", MayorVotingChatNotice)