Module:ServiceLink

From Against the Storm Official Wiki
Revision as of 14:25, 9 November 2024 by Aeredor (talk | contribs) (Whole rewrite; externalized the view; now uses the updated data models)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Documentation for this module may be created at Module:ServiceLink/doc

---
---@module ServiceLink
local ServiceLink = {}



--region Dependencies

---@type BaseDataModel
local InstitutionsData = require("Module:InstitutionsData")

local VIEW_TEMPLATE = "Service_link/view"

--endregion



--region Private constants

local VALID_SIZE = {
    ["none"] = true,
    ["small"] = true,
    ["medium"] = true,
    ["large"] = true,
    ["huge"] = true,
}

--endregion

--region Localization string constants

local ERROR_MESSAGE_INVALID_NAME = "You must specify a service. Please see the template documentation for how to use the parameters"
local ERROR_MESSAGE_INVALID_NAME = "The service you specified was not found. Please see the template documentation for how to use the parameters"

--endregion



--region Private methods

local function validateServiceNameByIcon(name)

    --Currently services have the same ID and name. Hopefully this doesn't change.
    local list = InstitutionsData:getIDsAndRecipesWhereProductID(name)

    --If the list is empty, then the name is not valid.
    if #list < 1 then
        error(ERROR_MESSAGE_INVALID_NAME)
    end

    return "Icon_Need_" .. name .. ".png"
end

--endregion



--region Public methods

---@public
---Extracts parameters, validates the service by getting its icon, and then sends the data to the view template for rendering.
---
---@param frame table the template's context, with arguments
---@return string wiki markup
function ServiceLink.main(frame)

    local name = frame.args.name
    local iconSize = frame.args.size
    local displayOverride = frame.args.display

    if not name or name == "" then
        error(ERROR_MESSAGE_INVALID_NAME)
    end

    --Validate the name
    validatedIcon = validateServiceNameByIcon(name)

    --Handle default icon size
    if not iconSize or iconSize == "" or not VALID_SIZE[iconSize] then
        iconSize = "small"
    end

    --The args to pass to the view.
    viewParameters = {
        ["name"] = name,
        ["iconfilename"] = validatedIcon,
        ["iconsize"] = iconSize,
        ["display"] = displayOverride,
    }

    return frame:expandTemplate{
        title = VIEW_TEMPLATE,
        args = viewParameters,
    }
end

--endregion

return ServiceLink