--[[
    UI/StablePanel.lua

    Your own pets, on screen instead of behind "/shiny stable".

    Reads the snapshot stored by Collection/StableScanner.lua, so it works away
    from a stable master and says when the reading was taken. A pet whose
    display id matches the database is marked as recognised and shows its family
    icon; one that does not is still listed, because it is yours either way.
]]

local _, ns = ...

local StablePanel = ns.NewModule("StablePanel")
ns.UI = ns.UI or {}
ns.UI.StablePanel = StablePanel

local OWNED_COLOR = { r = 0.35, g = 0.95, b = 0.35 }

--- Builds the panel into a parent frame.
-- @param parent Frame @return table Handle with Refresh().
function StablePanel:Create(parent)
    local panel = {}

    local frame = CreateFrame("Frame", nil, parent)
    frame:SetAllPoints(parent)
    panel.frame = frame

    panel.list = ns.UI.PetList:Create(frame)

    local empty = frame:CreateFontString(nil, "ARTWORK", "GameFontHighlight")
    empty:SetPoint("CENTER", frame, "CENTER", 0, 0)
    empty:SetWidth(420)
    empty:SetJustifyH("CENTER")
    empty:SetSpacing(3)
    empty:SetTextColor(0.6, 0.6, 0.6)
    panel.empty = empty

    --- Redraws from the stored stable snapshot.
    function panel:Refresh()
        local L = ns.L
        local API = ns.Data.API
        local State = ns.Collection.State

        local snapshot = State:GetStableSnapshot()

        if #snapshot == 0 then
            empty:SetText(L["STABLE_PANEL_NEVER"])
            empty:Show()
            self.list.container:Hide()
            return
        end

        empty:Hide()
        self.list.container:Show()

        local scannedAt = State:GetLastStableScan()
        local elements = {
            {
                kind = "header",
                name = L["STABLE_PANEL_HEADER"]:format(
                    scannedAt > 0 and date("%d/%m/%Y %H:%M", scannedAt) or "?"),
                counterText = tostring(#snapshot),
            },
        }

        for _, pet in ipairs(snapshot) do
            local appearanceID = pet.displayID
                and API:GetAppearanceIDByDisplayID(pet.displayID) or nil
            local family = appearanceID and API:GetFamilyOfAppearance(appearanceID) or nil

            -- Presence in the stable is first-party proof of ownership.  A
            -- missing database match is our data debt, never a reason to show
            -- the player's own pet as unknown or undiscovered.
            elements[#elements + 1] = {
                name = pet.name or "?",
                subtitle = pet.familyName,
                icon = family and family.icon or nil,
                portraitDisplayID = pet.displayID,
                desaturated = false,
                statusText = L["DETAIL_IN_STABLE"],
                statusColor = OWNED_COLOR,
            }
        end

        self.list:SetElements(elements)
    end

    panel:Refresh()

    return panel
end
