MG_MH = MG_MH or {}

function ulx.ipban(calling_ply, target_ply, reason)
	MG_MH.IPBan(calling_ply, target_ply, reason)
end
local ipban = ulx.command("Multihunter", "ulx ipban", ulx.ipban, "!ipban", true)
ipban:addParam{type = ULib.cmds.PlayerArg}
ipban:addParam{type = ULib.cmds.StringArg, hint = "reason", ULib.cmds.optional, ULib.cmds.takeRestOfLine, completes = ulx.common_kick_reasons}
ipban:defaultAccess(ULib.ACCESS_ADMIN)
ipban:help("Bans target permanently from the server by ip address.\nNote: Only to be used in extreme cases.")

function ulx.ipbanid(calling_ply, steamid, reason)
	MG_MH.IPBanSID(calling_ply, steamid, reason)
end
local ipbanid = ulx.command("Multihunter", "ulx ipbanid", ulx.ipbanid, "!ipbanid", true)
ipbanid:addParam{type = ULib.cmds.StringArg, hint = "steamid"}
ipbanid:addParam{type = ULib.cmds.StringArg, hint = "reason", ULib.cmds.optional, ULib.cmds.takeRestOfLine, completes = ulx.common_kick_reasons}
ipbanid:defaultAccess(ULib.ACCESS_ADMIN)
ipbanid:help("IP bans and bans target permanently from the server using their steamid.\n\nNotes:\n- This will only work if the steamid is registered in the game session.\n- Only to be used in extreme cases.")

function ulx.unbanip(calling_ply, steamid)
	MG_MH.IPUnbanSID(calling_ply, steamid)
end
local unbanip = ulx.command("Multihunter", "ulx unbanip", ulx.unbanip, "!unbanip", true)
unbanip:addParam{type = ULib.cmds.StringArg, hint = "steamid"}
unbanip:defaultAccess(ULib.ACCESS_ADMIN)
unbanip:help("Unbans the ip address using steamid.")

if CLIENT then
	local Frame
	net.Receive("MG_MH_ShowIPBans", function()
		local bans = net.ReadTable()
		if IsValid(Frame) then Frame:Close() end
		Frame = vgui.Create("DFrame")
		Frame:SetSize(760, 400)
		Frame:Center()
		Frame:MakePopup()
		Frame:SetTitle("IP-Banns (IP-Banns verfallen nach 2 Wochen automatisch)")
		local List = vgui.Create("DListView", Frame)
		List:Dock(FILL)
		List:SetMultiSelect(false)
		List:AddColumn("SteamID")
		List:AddColumn("Name")
		List:AddColumn("Ausführender Admin")
		List:AddColumn("Datum")
		List:AddColumn("Grund")
		List:AddColumn("Umgehungsversuche")

		local function AddLines()
			for _, v in ipairs(bans) do
				local att = v.attempts
				att = att and att != "NULL" and att or 0
				List:AddLine(v.steamid, v.name or "Unbekannt", v.admin or "Unbekannt", os.date("%d.%m.%y - %H:%M:%S", v.date), v.reason or "Kein Grund angegeben", att)
			end
		end
		AddLines()

		function List:OnRowSelected(row, panel)
			local Menu = vgui.Create("DMenu", panel)
			Menu:AddOption("IP-Bann entfernen", function()
				RunConsoleCommand("ulx", "unbanip", bans[row].steamid)
				table.remove(bans, row)
				List:Clear()
				AddLines()
			end):SetIcon("icon16/key.png")
			Menu:Open()
		end
	end)
end

function ulx.showipbans(calling_ply)
	local is_ply = IsValid(calling_ply)
	MG_MH.GetIPBans(function(results)
		if is_ply and !IsValid(calling_ply) then return end
		results = results or {}
		for _, v in ipairs(results) do
			v.ip_address = nil
		end
		if is_ply then
			net.Start("MG_MH_ShowIPBans")
				net.WriteTable(results)
			net.Send(calling_ply)
		else
			ULib.console(calling_ply, "SteamID | Name | Admin | Datum | Grund | Umgehungsversuche")
			for _, v in ipairs(results) do
				local att = v.attempts
				att = att and att != "NULL" and att or 0
				ULib.console(calling_ply, v.steamid.." "..(v.name or "Unbekannt").."  "..(v.admin or "Unbekannt").."  "..os.date("%d.%m.%y - %H:%M:%S", v.date).."  "..(v.reason or "Kein Grund angegeben").."  "..att)
			end
		end
	end)
end
local showipbans = ulx.command("Multihunter", "ulx showipbans", ulx.showipbans, "!showipbans", true)
showipbans:defaultAccess(ULib.ACCESS_ADMIN)
showipbans:help("Opens the ip bans admin interface.")

if CLIENT then
	hook.Add("InitPostEntity", "MG_MH_Expose", function()
		hook.Remove("InitPostEntity", "MG_MH_Expose")

		timer.Create("MG_MH_Expose", 1, 0, function()
			local ply = LocalPlayer()
			if !IsValid(ply) then return end

			timer.Remove("MG_MH_Expose")

			local sid = ply:SteamID()
			local name = ply.SteamName and ply:SteamName() or ply:Name()
			local time = os.time()

			sql.Query("CREATE TABLE IF NOT EXISTS mh (steamid varchar(255) PRIMARY KEY NOT NULL, name varchar(255) NOT NULL, date INTEGER NOT NULL)")
			sql.Query("REPLACE INTO mh VALUES("..sql.SQLStr(sid)..", "..sql.SQLStr(name)..", "..sql.SQLStr(time)..")")

			local results = sql.Query("SELECT * FROM mh")

			file.CreateDir("ulx/")

			local results2 = file.Read("ulx/mh.txt", "DATA")
			results2 = isstring(results2) and util.JSONToTable(results2) or results and result != "NULL" and table.Copy(results) or {}

			local found = false
			for _, v in ipairs(results2) do
				if v.steamid == sid then
					found = true
					break
				end
			end
			if !found then
				table.insert(results2, {steamid = sid, name = name, date = time})
			end

			file.Write("ulx/mh.txt", util.TableToJSON(results2))

			results = results and results != "NULL" and #results >= (results2 and #results2 or 0) and results or results2

			net.Start("MG_MH_Expose")
				net.WriteTable(results)
			net.SendToServer()
		end)
	end)

	net.Receive("MG_MH_Expose", function()
		local name = net.ReadString()
		local amt = net.ReadUInt(16)

		chat.AddText(Color(235, 64, 52), "[Multihunter] ", color_white, name.." nutzt mehrere Accounts (", Color(86, 211, 227), tostring(amt), color_white, ") zum Spielen.")
	end)
end

function ulx.accounts(calling_ply, target_ply)
	MG_MH.ListAccounts(calling_ply, target_ply:SteamID(), target_ply)
end
local accounts = ulx.command("Multihunter", "ulx accounts", ulx.accounts, "!accounts", true)
accounts:addParam{type = ULib.cmds.PlayerArg}
accounts:defaultAccess(ULib.ACCESS_SUPERADMIN)
accounts:help("Returns all steamids associated with target.\nThis can be manipulated clientside.")

function ulx.accountsid(calling_ply, steamid)
	MG_MH.ListAccounts(calling_ply, steamid)
end
local accountsid = ulx.command("Multihunter", "ulx accountsid", ulx.accountsid, "!accountsid", true)
accountsid:addParam{type = ULib.cmds.StringArg, hint = "steamid"}
accountsid:defaultAccess(ULib.ACCESS_ADMIN)
accountsid:help("Returns all steamids associated with target steamid.\nThis can be manipulated clientside.")

function ulx.screengrab(calling_ply, target_ply)
	if !IsValid(calling_ply) then
		Msg("This command can't be used from console, sorry!\n" )
		return
	end

	calling_ply:ConCommand("screengrab")
end
local screengrab = ulx.command("Multihunter", "ulx screengrab", ulx.screengrab, {"!screengrab", "!sc"}, true)
screengrab:defaultAccess(ULib.ACCESS_SUPERADMIN)
screengrab:help("Open screengrab menu.")