local addonName, TOAST = ...

local DUNGEON_SHORT = {
    ["Algeth'ar Academy"]       = "AA",
    ["Seat of the Triumvirate"] = "SOTT",
    ["Skyreach"]                = "SKY",
    ["Pit of Saron"]            = "PIT",
    ["Windrunner Spire"]        = "SPIRE",
    ["Maisara Caverns"]         = "CAVERN",
    ["Nexus-Point Xenas"]       = "XENAS",
    ["Magisters' Terrace"]      = "MT",
}

TOAST.keys = {}

C_ChatInfo.RegisterAddonMessagePrefix("TOAST")
C_ChatInfo.RegisterAddonMessagePrefix("LibKS")

local function BroadcastKey()
    local mapID = C_MythicPlus.GetOwnedKeystoneChallengeMapID()
    if not mapID or mapID == 0 then return end
    local level = C_MythicPlus.GetOwnedKeystoneLevel()
    local name  = C_ChallengeMode.GetMapUIInfo(mapID)
    name = name and name:match("^%s*(.-)%s*$") or ""
    local short = DUNGEON_SHORT[name] or name
    C_ChatInfo.SendAddonMessage("TOAST", "KEY:" .. level .. ":" .. short, "GUILD")
    local playerName = UnitName("player")
    TOAST.keys[playerName] = { level = level, short = short }
    TOAST_DB.keys[playerName] = { level = level, short = short }
end

local ev = CreateFrame("Frame")
ev:RegisterEvent("ADDON_LOADED")
ev:RegisterEvent("PLAYER_LOGIN")
ev:RegisterEvent("CHALLENGE_MODE_MAPS_UPDATE")
ev:RegisterEvent("CHAT_MSG_ADDON")
ev:SetScript("OnEvent", function(self, event, prefix, message, channel, sender)
    if event == "ADDON_LOADED" then
        if prefix ~= addonName then return end
        TOAST_DB = TOAST_DB or {}
        TOAST_DB.keys = TOAST_DB.keys or {}
        for k, v in pairs(TOAST_DB.keys) do
            TOAST.keys[k] = v
        end
        return
    end
    if event == "PLAYER_LOGIN" then
        BroadcastKey()
        C_ChatInfo.SendAddonMessage("TOAST", "KEY_REQUEST", "GUILD")
        C_ChatInfo.SendAddonMessage("LibKS", "R", "GUILD")
        return
    end
    if event == "CHALLENGE_MODE_MAPS_UPDATE" then
        BroadcastKey()
        return
    end
    -- CHAT_MSG_ADDON
    if prefix == "LibKS" then
        if message == "R" then
            local mapID = C_MythicPlus.GetOwnedKeystoneChallengeMapID()
            local level = C_MythicPlus.GetOwnedKeystoneLevel()
            local rating = 0
            local rs = C_PlayerInfo.GetPlayerMythicPlusRatingSummary("player")
            if rs and rs.currentSeasonScore then
                rating = rs.currentSeasonScore
            end
            if mapID and mapID > 0 then
                C_ChatInfo.SendAddonMessage("LibKS",
                    level .. "," .. mapID .. "," .. rating, "GUILD")
            end
            return
        end
        local levelStr, mapIDStr = message:match("^(%d+),(%d+),")
        if levelStr and mapIDStr then
            local level = tonumber(levelStr)
            local mapID = tonumber(mapIDStr)
            if level and level > 0 and mapID and mapID > 0 then
                local name = C_ChallengeMode.GetMapUIInfo(mapID)
                local short = DUNGEON_SHORT[name] or name
                local charName = sender:match("^([^%-]+)")
                if not TOAST.keys[charName] then
                    TOAST.keys[charName] = { level = level, short = short }
                    TOAST_DB.keys[charName] = { level = level, short = short }
                    if TOAST.RefreshKeyColumn then TOAST.RefreshKeyColumn() end
                end
            end
        end
        return
    end
    if prefix ~= "TOAST" then return end
    if message == "KEY_REQUEST" then
        BroadcastKey()
        return
    end
    if not message:match("^KEY:") then return end
    local payload = message:sub(5)
    local level, short = payload:match("^(%d+):(.+)$")
    if not level then return end
    local charName = sender:match("^([^%-]+)")
    TOAST.keys[charName] = { level = tonumber(level), short = short }
    TOAST_DB.keys[charName] = { level = tonumber(level), short = short }
    if TOAST.RefreshKeyColumn then TOAST.RefreshKeyColumn() end
end)
