-- TICKER_200
function()
	if not WeakAurasSaved.Cyka then WeakAurasSaved.Cyka = {} end
	if not WeakAurasSaved.Cyka.MessageQueue then WeakAurasSaved.Cyka.MessageQueue = {} end

	---@type Message
	local message = WeakAurasSaved.Cyka.MessageQueue[1]
	if not message then return end
    if not message.message or message.message == "" then return end
    if not message.channel or message.channel == "" then return end

    -- Map channel names to ids
    if message.channel == "CHANNEL" and message.data and string.match(message.data, "%D") then
        print("Channel presented as string:", message.data)
        local channelId = aura_env.channelIdMap[message.data]
        if not channelId then
            print("Channel not found, scanning")
            aura_env.ScanChannels()
            channelId = aura_env.channelIdMap[message.data]
        end
        if not channelId then
            print("Channel not joined, joining")
            channelId = aura_env.FindOrJoinChannel(message.data)
        end
        print("Channel resolved to id", channelId)
        message.data = channelId
    end

	table.remove(WeakAurasSaved.Cyka.MessageQueue, 1)
	SendChatMessage(message.message, message.channel, nil, message.data)
end

--INIT
---@type table<string, number>
aura_env.channelIdMap = {}
aura_env.FindOrJoinChannel = function(channelName, password)
    local function GetChannelId(channelName)
        local channels = {GetChannelList()}
        for i = 1, #channels, 2 do
            local id = channels[i]
            local name = channels[i + 1]
            if name == channelName then
                return id
            end
        end
    end

    local channelId = GetChannelId(channelName)
    if not channelId then
        print("Channel", channelName, "not found, joining")
        if password then
            JoinPermanentChannel(channelName, password)
        else
            JoinPermanentChannel(channelName)
        end
    end
    channelId = GetChannelId(channelName)
    aura_env.channelIdMap[channelName] = channelId
    return channelId
end
aura_env.ScanChannels = function()
    local channels = {GetChannelList()}
    for i = 1, #channels, 2 do
        local id = channels[i]
        local name = channels[i + 1]
        aura_env.channelIdMap[name] = id
    end
end
local channelId = aura_env.FindOrJoinChannel(aura_env.config.channel, aura_env.config.channelPassword)
print("Channel", aura_env.config.channel, "resolved to id", channelId)
--aura_env.iterator = 0
--WeakAurasSaved.Cyka.MessageQueue = {}
--for i = 1, 100 do
--	table.insert(WeakAurasSaved.Cyka.MessageQueue, {
--		channel = "CHANNEL",
--		data = aura_env.channelId,
--		message = "TEST" .. i
--	})
--end
