Roovet Articles

Module:RoovetData

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

local p = {}

local function trim(value)
    if value == nil then
        return ''
    end

    return mw.text.trim(tostring(value))
end

local function mergeArgs(frame)
    local args = {}
    local parent = frame:getParent()

    if parent then
        for key, value in pairs(parent.args) do
            if value ~= nil and value ~= '' then
                args[key] = value
            end
        end
    end

    for key, value in pairs(frame.args) do
        if value ~= nil and value ~= '' then
            args[key] = value
        end
    end

    return args
end

local function fallback(args)
    return args.fallback or args[2] or ''
end

local function resolveEntity(args)
    local itemId = trim(args.item or args.qid)

    if itemId == '' then
        local ok, currentId = pcall(
            mw.wikibase.getEntityIdForCurrentPage
        )

        if ok then
            itemId = trim(currentId)
        end
    end

    if itemId == '' then
        return nil, nil
    end

    local ok, entity = pcall(
        mw.wikibase.getEntity,
        itemId
    )

    if not ok or not entity then
        return nil, itemId
    end

    return entity, itemId
end

local function formattedProperty(entity, propertyId)
    local ok, result = pcall(
        entity.formatPropertyValues,
        entity,
        propertyId
    )

    if not ok or type(result) ~= 'table' then
        return nil
    end

    local value = result.value

    if value == nil or trim(value) == '' then
        return nil
    end

    return value
end

function p.value(frame)
    local args = mergeArgs(frame)
    local propertyId = trim(args.property or args[1])

    if propertyId == '' then
        return fallback(args)
    end

    local entity = resolveEntity(args)

    if not entity then
        return fallback(args)
    end

    local value = formattedProperty(entity, propertyId)

    if not value then
        return fallback(args)
    end

    return (args.prefix or '') .. value .. (args.suffix or '')
end

function p.qid(frame)
    local args = mergeArgs(frame)
    local _, itemId = resolveEntity(args)

    if not itemId then
        return fallback(args)
    end

    return itemId
end

function p.has(frame)
    local args = mergeArgs(frame)
    local propertyId = trim(args.property or args[1])

    if propertyId == '' then
        return args.no or ''
    end

    local entity = resolveEntity(args)

    if not entity then
        return args.no or ''
    end

    local value = formattedProperty(entity, propertyId)

    if value then
        return args.yes or '1'
    end

    return args.no or ''
end

return p