MG_Watchlist = MG_Watchlist or {}

MG_Watchlist.TitleMaxSize = 50
MG_Watchlist.BodyMaxSize = 500

if CLIENT then
	local base, base2
	net.Receive("mg_watchlist_sendentries", function()
		local SID, Results = net.ReadString(), net.ReadTable()
		local PlyObject = player.GetBySteamID(SID)
		if !IsValid(base) then
			base = vgui.Create("DFrame")
			base:SetSize(760, 400)
			base:Center()
			base:SetTitle("Watchlist von "..(PlyObject and PlyObject:Name() or SID))
			base:MakePopup()
		else
			local basex, basey = base:GetPos()
			base:Close()
			base = vgui.Create("DFrame")
			base:SetSize(760, 400)
			base:SetPos(basex, basey)
			base:SetTitle("Watchlist von "..(PlyObject and PlyObject:Name() or SID))
			base:MakePopup()
		end

		local EntryList = vgui.Create("DListView", base)
		EntryList:Dock(FILL)
		EntryList:AddColumn("ID"):SetFixedWidth(100)
		EntryList:AddColumn("Admin")
		EntryList:AddColumn("Titel")
		EntryList:AddColumn("Datum")
		EntryList.OnRowRightClick = function(_, _, line)
			local context = vgui.Create("DMenu", base)
			context:AddOption("Erweiterte Ansicht", function()
				net.Start("mg_watchlist_requestextendedview")
					net.WriteUInt(line:GetValue(1), 32)
				net.SendToServer()
			end):SetIcon("icon16/magnifier.png")
			context:AddOption("Eintrag löschen", function()
				net.Start("mg_watchlist_removeentry")
					net.WriteString(line:GetValue(1))
					net.WriteString(SID)
				net.SendToServer()
			end):SetIcon("icon16/delete.png")
			if LocalPlayer():IsSuperAdmin() then
				context:AddOption("Alle Einträge löschen", function()
					net.Start("mg_watchlist_removeentry")
						net.WriteString("")
						net.WriteString(SID)
					net.SendToServer()
				end):SetIcon("icon16/shield_delete.png")
			end
			context:Open()
		end
		for k, v in ipairs(Results) do
			EntryList:AddLine(v.id, v.admin, v.title, os.date("%d.%m.%Y %H:%M:%S", v.created_on))
		end

		AddEntryBttn = vgui.Create("DButton", base)
		AddEntryBttn:Dock(BOTTOM)
		AddEntryBttn:SetText("Eintrag hinzufügen")
		AddEntryBttn.DoClick = function()
			if IsValid(base2) then return end
			base2 = vgui.Create("DFrame")
			base2:SetSize(600, 270)
			base2:SetTitle("Eintrag hinzufügen | "..(IsValid(PlyObject) and PlyObject:Name() or SID))
			base2:Center()
			base2:MakePopup()
			base2:SetParent(base)

			local BackgroundPanel = vgui.Create("DPanel", base2)
			BackgroundPanel:Dock(FILL)
			BackgroundPanel:DockPadding(5, 5, 5, 5)
			BackgroundPanel.Paint = function(self, w, h)
				draw.RoundedBox(0, 0, 0, w, h, Color(50, 50, 50))
			end

			local TitleLabel = vgui.Create("DLabel", BackgroundPanel)
			TitleLabel:Dock(TOP)
			TitleLabel:SetText("Titel")

			local TitleEntry = vgui.Create("DTextEntry", BackgroundPanel)
			TitleEntry:DockMargin(0, 0, 0, 10)
			TitleEntry:Dock(TOP)
			TitleEntry:SetPlaceholderText("Maximal "..MG_Watchlist.TitleMaxSize.." Zeichen")

			local BodyTitle = vgui.Create("DLabel", BackgroundPanel)
			BodyTitle:Dock(TOP)
			BodyTitle:SetText("Beschreibung (Optional)")

			local BodyEntry = vgui.Create("DTextEntry", BackgroundPanel)
			BodyEntry:SetTall(120)
			BodyEntry:Dock(TOP)
			BodyEntry:SetMultiline(true)
			BodyEntry:SetPlaceholderText("Maximal "..MG_Watchlist.BodyMaxSize.." Zeichen")

			local AddBttn = vgui.Create("DButton", BackgroundPanel)
			AddBttn:Dock(BOTTOM)
			AddBttn:SetText("Eintrag hinzufügen")
			AddBttn.DoClick = function()
				local val = string.Trim(TitleEntry:GetValue())
				local body = string.Trim(BodyEntry:GetValue())
				if #val < 1 then
					LocalPlayer():ChatPrint("Es wurde kein Titel angegeben!")
					surface.PlaySound("buttons/lightswitch2.wav")
					return
				elseif #val > MG_Watchlist.TitleMaxSize then
					LocalPlayer():ChatPrint("Der Titel ist zu lang.\nNutze die Beschreibung für längere Ausführungen!")
					surface.PlaySound("buttons/lightswitch2.wav")
					return
				elseif #body > MG_Watchlist.BodyMaxSize then
					LocalPlayer():ChatPrint("Die Beschreibung ist zu lang!")
					surface.PlaySound("buttons/lightswitch2.wav")
					return
				end
				net.Start("mg_watchlist_addentry")
					net.WriteString(SID)
					net.WriteString(val)
					net.WriteString(body)
				net.SendToServer()
				base2:Close()
			end
		end
	end)

	net.Receive("mg_watchlist_sendextendedview", function()
		local Title, Body = net.ReadString(), net.ReadString()
		local base3 = vgui.Create("DFrame")
		base3:SetSize(600, 240)
		base3:Center()
		base3:SetTitle("Erweiterte Ansicht")
		base3:MakePopup()
		if IsValid(base) then base3:SetParent(base) end

		local BackgroundPanel = vgui.Create("DPanel", base3)
		BackgroundPanel:Dock(FILL)
		BackgroundPanel:DockPadding(5, 5, 5, 5)
		BackgroundPanel.Paint = function(self, w, h)
			draw.RoundedBox(0, 0, 0, w, h, Color(50, 50, 50))
		end

		local TitleLabel = vgui.Create("DLabel", BackgroundPanel)
		TitleLabel:Dock(TOP)
		TitleLabel:SetText("Titel")

		local TitleEntry = vgui.Create("DTextEntry", BackgroundPanel)
		TitleEntry:DockMargin(0, 0, 0, 10)
		TitleEntry:Dock(TOP)
		TitleEntry:SetValue(Title)
		TitleEntry.AllowInput = function()
			return true
		end

		local BodyTitle = vgui.Create("DLabel", BackgroundPanel)
		BodyTitle:Dock(TOP)
		BodyTitle:SetText("Beschreibung")

		local BodyEntry = vgui.Create("DTextEntry", BackgroundPanel)
		BodyEntry:SetTall(120)
		BodyEntry:Dock(TOP)
		BodyEntry:SetMultiline(true)
		BodyEntry:SetValue(Body)
		BodyEntry.AllowInput = function()
			return true
		end
	end)
end

function ulx.watchlist(calling_ply, target_ply)
	if !calling_ply:IsValid() then
		Msg("You can't open the watchlist from the dedicated server console.\n")
		return
	end
	MG_Watchlist.RequestEntries(calling_ply, target_ply:SteamID())
end
local watchlist = ulx.command("Watchlist", "ulx watchlist", ulx.watchlist, "!watchlist", true)
watchlist:addParam{type=ULib.cmds.PlayerArg}
watchlist:help("Opens the watchlist of target.")
watchlist:defaultAccess(ULib.ACCESS_ADMIN)

function ulx.watchlistid(calling_ply, TargetSID)
	if !calling_ply:IsValid() then
		Msg("You can't open the watchlist from the dedicated server console.\n")
		return
	end
	if !ULib.isValidSteamID(TargetSID) then ULib.tsayError(calling_ply, "Invalid steamid.") return end
	MG_Watchlist.RequestEntries(calling_ply, TargetSID)
end
local watchlistid = ulx.command("Watchlist", "ulx watchlistid", ulx.watchlistid, "!watchlistid", true)
watchlistid:addParam{type=ULib.cmds.StringArg, hint="SteamID"}
watchlistid:help("Opens the watchlist of target, using steamid.")
watchlistid:defaultAccess(ULib.ACCESS_ADMIN)