MG_ChatHistory = {}
MG_ChatHistory.MaxLength = 25

MG_ChatHistory.History = {}


hook.Add("StartChat", "MG_ChatHistoryStart", function()
	local wasPressed1 = false
	local wasPressed2 = false
	local currentHistoryPosition = 0

	local currentText = ""

	hook.Add("ChatTextChanged", "MG_ChatHistory", function(text)
		currentText = text
	end, HOOK_MONITOR_HIGH or -2)

	hook.Add("FinishChat", "MG_ChatHistory", function()
		currentText = string.Trim(currentText)
		if currentText != "" and #currentText >= 3 then
			table.insert(MG_ChatHistory.History, 1, currentText)

			if #MG_ChatHistory.History > MG_ChatHistory.MaxLength then
				table.remove(MG_ChatHistory.History, #MG_ChatHistory.History)
			end
		end
	end, HOOK_MONITOR_HIGH or -2)

	local function SelectChatHistoryPosition(add)
		if add then
			currentHistoryPosition = currentHistoryPosition + 1
			if !MG_ChatHistory.History[currentHistoryPosition] then
				currentHistoryPosition = 1
			end
		else
			currentHistoryPosition = currentHistoryPosition - 1
			if !MG_ChatHistory.History[currentHistoryPosition] then
				currentHistoryPosition = #MG_ChatHistory.History
			end
		end

		if MG_ChatHistory.History[currentHistoryPosition] then
			SetClipboardText(MG_ChatHistory.History[currentHistoryPosition])

			chat.AddText(color_white, "\"", Color(115, 250, 243), MG_ChatHistory.History[currentHistoryPosition], color_white, "\" in Zwischenablage kopiert.\n", Color(255, 148, 56), "Position: "..currentHistoryPosition.."/"..#MG_ChatHistory.History, color_white, ", ", Color(36, 92, 138), "[STRG + V] zum Einfügen.")
		end
	end

	hook.Add("Think", "MG_ChatHistory", function()
		if input.IsKeyDown(KEY_UP) then
			if wasPressed1 then return end
			wasPressed1 = true

			SelectChatHistoryPosition(true)
		else
			wasPressed1 = false
		end

		if input.IsKeyDown(KEY_DOWN) then
			if wasPressed2 then return end
			wasPressed2 = true

			SelectChatHistoryPosition(false)
		else
			wasPressed2 = false
		end
	end)
end, HOOK_MONITOR_HIGH or -2)

hook.Add("FinishChat", "MG_ChatHistoryEnd", function()
	hook.Remove("ChatTextChanged", "MG_ChatHistory")
	hook.Remove("FinishChat", "MG_ChatHistory")
	hook.Remove("Think", "MG_ChatHistory")
end, HOOK_MONITOR_HIGH or -2)