local use_font = system.IsWindows() and "Tahoma" or "Verdana"
surface.CreateFont("MGMarker_BoxTitleFont", {font = use_font, size = 19, weight = 1000, blursize = 0, scanlines = 0, antialias = true})
surface.CreateFont("MGMarker_BoxFont", {font = use_font, size = 13, weight = 1000, blursize = 0, scanlines = 0, antialias = true})
surface.CreateFont("MGMarker_CloseFont", {font = use_font, size = 13, weight = 1000, blursize = 0, scanlines = 0, antialias = true})
surface.CreateFont("MGMarker_MarkerFont", {font = "Arial", size = 18, weight = 1000, antialias = true})

local markertime, desclength, calls, providers = mg_marker.config.markertime, mg_marker.config.desclength, {}
local names = {}
timer.Simple(0, function()
	providers = mg_marker.config.providers
	for k, v in pairs(providers) do
		if names[v.name] then continue end
		names[v.name] = true
	end
end)
local placeholder = string.format(mg_marker.config.placeholder, desclength)

local function callservice(mtype, mdesc, tracking)
	net.Start("mg_marker_net_servicereq")
		net.WriteString(mtype)
		net.WriteString(mdesc or "")
		net.WriteBool(tracking)
	net.SendToServer()
end

local mframe
local function openservices()
	if IsValid(mframe) then return end
	mframe = vgui.Create("DFrame")
	mframe:SetSize(450, 240)
	mframe:Center()
	mframe:SetTitle("")
	mframe:ShowCloseButton(false)
	mframe:MakePopup()
	mframe:ParentToHUD()
	mframe.Paint = function(self, w, h)
		draw.RoundedBox(0, 0, 0, w, h, Color(224, 224, 224, 255))
		draw.RoundedBox(0, 1, 1, w - 2, h - 2, Color(250, 250, 250, 255))
		draw.RoundedBox(0, 0, 0, w, 50, Color(62, 67, 77))
		draw.SimpleText("Service rufen", "MGMarker_BoxTitleFont", 20, 15, color_white)
		surface.SetDrawColor(Color(84, 89, 100, 255))
		surface.DrawLine(1, 1, w - 2, 1)
		surface.DrawLine(1, 1, 1, 49)
		surface.DrawLine(w - 2, 1, w - 2, 49)
	end

	local mclsbttn = vgui.Create("DButton", mframe)
	mclsbttn:SetSize(50, 20)
	mclsbttn:SetPos(mframe:GetWide() - 60, 0)
	mclsbttn:SetText("X")
	mclsbttn:SetFont("MGMarker_CloseFont")
	mclsbttn:SetTextColor(color_white)
	mclsbttn.Paint = function(self, w, h)
		local kcol
		if self:IsHovered() then
			kcol = Color(255, 150, 150, 255)
		else
			kcol = Color(175, 100, 100)
		end
		draw.RoundedBoxEx(0, 0, 0, w, h, Color(255, 150, 150, 255), false, false, true, true)
		draw.RoundedBoxEx(0, 1, 0, w - 2, h - 1, kcol, false, false, true, true)
	end
	mclsbttn.DoClick = function()
		mframe:Close()
	end

	local mcombo = vgui.Create("DComboBox", mframe)
	mcombo:Dock(TOP)
	mcombo:DockMargin(0, 30, 0, 15)
	mcombo:SetValue("Typ der Anfrage")
	for k, v in pairs(names) do
		mcombo:AddChoice(k)
	end

	local mlabel = vgui.Create("DLabel", mframe)
	mlabel:Dock(TOP)
	mlabel:DockMargin(0, 0, 0, 5)
	mlabel:SetText("Beschreibung der Anfrage (Optional)")
	mlabel:SetDark(true)

	local mtextentry = vgui.Create("DTextEntry", mframe)
	mtextentry:Dock(TOP)
	mtextentry:SetTall(50)
	mtextentry:SetMultiline(true)
	mtextentry:SetPlaceholderText(placeholder)

	local mcheckbox = vgui.Create("DCheckBoxLabel", mframe)
	mcheckbox:SetPos(5, 186)
	mcheckbox:SetText("Live-Standort für die Länge des Calls aktivieren?")
	mcheckbox:SetDark(true)

	local mbttn = vgui.Create("DButton", mframe)
	mbttn:Dock(BOTTOM)
	mbttn:SetText("Anfrage aufgeben")
	mbttn:SetTextColor(Color(255,255,255))
	mbttn.Paint = function(self, w, h)
		local col
		if self:IsHovered() then
			col = Color(36, 190, 255)
		else
			col = Color(36, 165, 221)
		end
		draw.RoundedBox(0, 0, 0, w, h, Color(16, 96, 130))
		draw.RoundedBox(0, 1, 1, w - 2, h - 2, col)
	end
	mbttn.DoClick = function()
		if !mcombo:GetSelected() then
			LocalPlayer():ChatPrint("Du musst einen Typ auswählen!")
			return
		end
		if #mtextentry:GetValue() > desclength then
			LocalPlayer():ChatPrint("Beschreibung zu lang!")
			return
		end
		callservice(mcombo:GetSelected(), Either(#mtextentry:GetValue() < 1, nil, mtextentry:GetValue()), mcheckbox:GetChecked())
		mframe:Remove()
	end
end

local function IsOnScreen(pos)
	local pos_x = pos.x
	local pos_y = pos.y
	return pos_x > 0 and pos_x < ScrW() and pos_y > 0 and pos_y < ScrH()
end

local function drawmarkers()
	if #calls < 1 then hook.Remove("HUDPaint", "mg_marker_hooks_hudpaint") return end
	local ply = LocalPlayer()
	for k, v in pairs(calls) do
		if !IsValid(v.ply) or v.tm != ply:Team() then
			calls[k] = nil
			continue
		end
		if CurTime() >= v.time then
			calls[k] = nil
			continue
		end
		local pos, epos = v.pos, ply:EyePos()
		if v.tracking then
			v.pos = v.ply:EyePos()
			pos = v.ply:EyePos()
		end
		pos = pos:ToScreen()
		if IsOnScreen(pos) then
			surface.SetDrawColor(color_white)
			surface.SetMaterial(v.icon)
			surface.DrawTexturedRect(pos.x - 18, pos.y - 16, 42, 42)
			draw.SimpleTextOutlined(v.ply:Name(), "MGMarker_MarkerFont", pos.x, pos.y + 37, team.GetColor(v.ply:Team()), TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, color_black)
			draw.SimpleTextOutlined(math.floor(epos:Distance(v.pos) * 0.0254) .."m", "MGMarker_MarkerFont", pos.x, pos.y + 56, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, color_black)
			draw.SimpleTextOutlined("Zeit: "..string.ToMinutesSeconds(math.max(0, v.time - CurTime())).." - ID: "..k, "MGMarker_MarkerFont", pos.x, pos.y + 75, color_white, TEXT_ALIGN_CENTER, TEXT_ALIGN_CENTER, 1, color_black)
		end
	end
end

net.Receive("mg_marker_net_addmarker", function()
	local mtype, ply, tracking = net.ReadString(), net.ReadEntity(), net.ReadBool()
	if !ply:IsPlayer() then return end
	if #calls < 1 then
		hook.Add("HUDPaint", "mg_marker_hooks_hudpaint", drawmarkers)
	end
	for k, v in pairs(providers) do
		if v.name != mtype then continue end
		calls[#calls + 1] = {
			icon = v.icon,
			time = CurTime() + markertime,
			tracking = tracking,
			pos = ply:EyePos(),
			ply = ply,
			tm = LocalPlayer():Team()
		}
		break
	end
	surface.PlaySound("buttons/button14.wav")
end)

net.Receive("mg_marker_net_removemarker", function()
	local num = net.ReadUInt(7)
	if !calls[num] then
		LocalPlayer():ChatPrint("Kein Marker mit dieser ID existiert!")
		return
	end
	calls[num] = nil
	LocalPlayer():ChatPrint("Marker (ID: "..num..") entfernt.!")
end)

net.Receive("mg_marker_net_removemarkers", function()
	calls = {}
	LocalPlayer():ChatPrint("Alle Marker entfernt.")
end)

concommand.Add("marker_sys", function()
	openservices()
end)