---@diagnostic disable: undefined-field
-- CHAT_MSG_CHANNEL TICKER_1000
---@param allstates allstates
function(allstates, e, ...)
	if e == "CHAT_MSG_CHANNEL" then
		local message, author, _, channel = ...
		if message == nil or author == nil then return end
		if string.find(message, "Hkeystone") then
			local keyid, level = string.match(message, "Hkeystone:(%d+):(%d+)")
			if keyid == nil or level == nil then return end
			keyid = tonumber(keyid)
			level = tonumber(level)
			---@cast keyid number
			---@cast level number
			author = string.gsub(author, "%-.+$", "")

			local keyname = aura_env.KeystoneIdMap[keyid]
			if keyname == nil then
				DevTools_Dump({ "Failed getting key name from", keyid, level, message })
				return
			end
			---@cast keyname string

			local keykeyname = string.gsub(keyname, " ", "_")
			keykeyname = string.gsub(keykeyname, "'", "")
			keykeyname = string.gsub(keykeyname, ":", "")
			local targetLevel = aura_env.config[keykeyname] or 15
			local leveldelta = level - targetLevel

			local color, _ = aura_env.Colorer.Interpolate(leveldelta)
			local r = math.floor(color.r * 255)
			local g = math.floor(color.g * 255)
			local b = math.floor(color.b * 255)
			local hexColor = string.format("%02x%02x%02x", r, g, b)
			-- For some reason Colorer.RGBToHex does not work with some strange lua error
			-- It works when ran standalone with lua54 but not in a weakaura
			-- Whatever...
			local formattedName = string.format("|cFF%s%s|r", hexColor, keyname)
			allstates[author .. keyid .. level] = {
				show = true,
				changed = true,
				keyid = keyid,
				level = level,
				targetLevel = targetLevel,
				leveldelta = leveldelta,
				name = formattedName,
				keyname = keyname,
				color = color,
				-- tooltip = message, -- Tooltip doesn't work for some reason...
				author = author,
				channel = channel,
				progressType = "timed",
				duration = 60,
				expirationTime = GetTime() + 60,
				autohide = true,
				index = GetTime(),
				progress = "0s",
			}
			return true
		end
	else
		if e == "TICKER_1000" then
			local ttl = aura_env.config.expirationtime
			for _, state in pairs(allstates) do
				if state.progress then
					local elapsedTime = GetTime() - state.index
					if elapsedTime > ttl then
						state.show = false
						state.changed = true
					else
						local prettyTime = ""

						local minutes = 0
						while elapsedTime > 60 do
							elapsedTime = elapsedTime - 60
							minutes = minutes + 1
						end
						if minutes > 0 then
							prettyTime = string.format("%s%dm", prettyTime, minutes)
						end
						if elapsedTime > 0 then
							prettyTime = string.format("%s %ds", prettyTime, elapsedTime)
						end
						state.progress = prettyTime
						state.changed = true
					end
				end
			end
		end
		return true
	end
end
