Модуль:Prototypes/Хранилище/Предмет

Материал из Space Station 14 Вики

Для документации этого модуля может быть создана страница Модуль:Prototypes/Хранилище/Предмет/doc

-- Загрузка данных
local itemData      = mw.loadData("Модуль:IanComradeBot/prototypes/fills/Item.json/data")
local itemSlotsData = mw.loadData("Модуль:IanComradeBot/prototypes/ItemSlots.json/data")
local chemData      = mw.loadData("Модуль:IanComradeBot/prototypes/fills/chem.json/data")

local p = {}

-- Функция для загрузки данных 
local loadData = function(filePath)
    local page = mw.title.new(filePath)
    local content = page:getContent()
    return content and mw.text.jsonDecode(content) or nil
end

-- Функция processRolls для преобразования диапазона
local processRolls = function(rolls)
    local result = ""
    if rolls and rolls.range then
        -- Если указан range
        local min, max = rolls.range:match("(%d+),%s*(%d+)")
        min, max = tonumber(min), tonumber(max)
        if min and max then
            result = result .. string.format('[%d-%d]', min + 1, max + 1)
        else
            result = result .. 'Некорректный формат для range.'
        end
    elseif rolls and rolls.value then
        -- Если указано value
        result = result .. string.format('[%d]', rolls.value)
    else
        result = result .. 'Не указан параметр rolls.'
    end
    return result
end

-- Функция для поиска первого startingItem в slots
local function getFirstStartingItem(data)
    if not data or not data.ItemSlots or not data.ItemSlots.slots then 
        return nil 
    end
    
    for _, slot in pairs(data.ItemSlots.slots) do
        if slot.startingItem and slot.startingItem ~= "" then
            return slot.startingItem
        end
    end
    
    return nil
end


-- Локальные функции
local findDataById, formatContent, getContentsOutput, processNestedSelectors, getTableOutput, getContainedOutput, getChemOutput, handleGroupSelector, handleAllSelector, handleNestedSelector

-- Поиск данных по ID через индекс
findDataById = function(itemDataIndex, id)
    if not itemDataIndex then return nil end
	for _, item in ipairs(itemDataIndex) do
		if item.id == id then
			return item
		end
	end
end

-- Форматирование содержимого
formatContent = function(content)
    if type(content) == "table" and not content.id then
        return "Ошибка: отсутствует id у элемента."
    end

    local id = content.id or content
    
    local amountNumber = 1
    if content.amount then
        if type(content.amount) == "table" then
            amountNumber = content.amount.value or 1
        else
            amountNumber = content.amount
        end
    end
    local amount = (amountNumber and amountNumber ~= 1) and string.format(" [%d]", amountNumber) or ""
    
    local prob = ""

    if content.weight then
        content.prob = content.weight / 100
    end

    if content.prob then
        prob = string.format(" <div>%s%%</div>", content.prob * 100 >= 1 and math.floor(content.prob * 100) or content.prob * 100)
    end

    return string.format(
        '{{Шаблон:LinkСard/Предмет|%s|%s%s}}',
        id, amount, prob
    )
end

-- Получение содержимого через таблицу
getContentsOutput = function(contents)
    local result = ""
    for _, content in ipairs(contents) do
        result = result .. formatContent(content)
    end
    return result
end

-- Обработка вложенных таблиц
processNestedSelectors = function(children, visited)
	visited = visited or {}
    if not children or #children == 0 then return "" end

    local result = ""

    for _, child in ipairs(children) do
        if child.id then
			if not visited[child.id] then
			    result = result .. formatContent(child)
			end
        elseif child["!type"] == "NestedSelector" then
            result = result .. handleNestedSelector(child, true, visited)
        elseif child["!type"] == "GroupSelector" then
            result = result .. handleGroupSelector(child, visited)
        end
    end

    return result
end

-- Обработка таблиц
getTableOutput = function(tableId, visited)
    visited = visited or {}

    if visited[tableId] then
        return ''
    end

    visited[tableId] = true

    local tableData = loadData('User:IanComradeBot/prototypes/table.json')
    local tableDataIndex = findDataById(tableData, tableId)

    if not tableDataIndex then return 'Таблица не найдена.' end

    if tableDataIndex['!type:GroupSelector'] then
        return handleGroupSelector(tableDataIndex['!type:GroupSelector'], visited)
    elseif tableDataIndex['!type:AllSelector'] then
        return processNestedSelectors(tableDataIndex['!type:AllSelector'].children, visited)
    end

    return 'Таблица не содержит элементов.'
end

-- Формирование списка содержащихся предметов или таблиц
getContainedOutput = function(itemData, id, visited)
    visited = visited or {} 

    if visited[id] then
        return ''
    end

    visited[id] = true

    local item = findDataById(itemData, id)
    if not item then return '' end

    local result = {}

    -- Обработка StorageFill
    if item.StorageFill and item.StorageFill.contents then
        result[#result + 1] = getContentsOutput(item.StorageFill.contents)

    -- Обработка EntityTableContainerFill
    elseif item.EntityTableContainerFill and item.EntityTableContainerFill.containers then
        local containers = item.EntityTableContainerFill.containers

        -- Обработка entity_storage
        if containers.entity_storage then
            -- Если есть просто элементы с id, то форматируем их как обычные предметы
            if containers.entity_storage.children then
                for _, child in ipairs(containers.entity_storage.children) do
                    if child.id then
                        result[#result + 1] = formatContent(child) -- Теперь одиночные id не игнорируются
                    elseif child["!type"] == "GroupSelector" then
                        result[#result + 1] = handleGroupSelector(child, visited)
                    elseif child["!type"] == "AllSelector" then
                        result[#result + 1] = processNestedSelectors(child.children, visited)
                    end
                end
            end

            -- Если есть таблица, то загружаем её
            if containers.entity_storage.tableId then
                result[#result + 1] = getTableOutput(containers.entity_storage.tableId, visited)
            end
        end

        -- Обработка storagebase (аналогично entity_storage)
        if containers.storagebase then
            if containers.storagebase.children then
                for _, child in ipairs(containers.storagebase.children) do
                    if child.id then
                        result[#result + 1] = formatContent(child)
                    elseif child["!type"] == "GroupSelector" then
                        result[#result + 1] = handleGroupSelector(child, visited)
                    elseif child["!type"] == "AllSelector" then
                        result[#result + 1] = processNestedSelectors(child.children, visited)
                    end
                end
            end

            if containers.storagebase.tableId then
                result[#result + 1] = getTableOutput(containers.storagebase.tableId, visited)
            end
        end
    end

    return table.concat(result)
end

-- Обработка AllSelector
handleAllSelector = function(allSelector)
    if not allSelector.children then return '' end
    return processNestedSelectors(allSelector.children)
end

-- Обработка GroupSelector
handleGroupSelector = function(groupSelector)
    if not groupSelector.children then return '' end
    local result = ""
    local wrapperStart, wrapperEnd = "", ""

    -- Проверка для контейнера EntityTableContainerFill
    if groupSelector.weight and groupSelector.weight ~= "default" then
        wrapperStart = string.format('{{LinkСard/Сollapsible|name=Группа предметов %s%%|content=', groupSelector.weight)
        wrapperEnd = "}}"
    elseif groupSelector["!type"] == "GroupSelector" and not groupSelector.weight then
        wrapperStart = '{{LinkСard/Сollapsible|name=Может выпасть лишь один из:|content='
        wrapperEnd = "}}"
    end

    for _, child in ipairs(groupSelector.children) do
        if child["!type"] == "GroupSelector" then
            result = result .. handleGroupSelector(child)
        elseif child["!type"] == "AllSelector" then
            result = result .. string.format('{{LinkСard/Сollapsible|name=Выпадают только вместе:|content=%s}}', handleAllSelector(child))
        elseif child.id then
            result = result .. formatContent(child)
        else
            result = result .. "<div>Ошибка: отсутствует id у элемента.</div>"
        end
    end

    return wrapperStart .. result .. wrapperEnd
end

-- Обработка NestedSelector
handleNestedSelector = function(nestedSelector, wrapped, visited)
	visited = visited or {}
    if not nestedSelector.tableId then return '' end

    local result = ""
    local classesRolls, classesProb

    if wrapped then
        if nestedSelector.rolls and nestedSelector.rolls.range then
            local rollsResult = processRolls(nestedSelector.rolls)
            if rollsResult and #rollsResult > 0 then
                classesRolls = ', максимум может выпасть: ' .. rollsResult
            end
        end
        if nestedSelector.prob then
            classesProb = string.format(" <div>%s%%</div>", nestedSelector.prob * 100 >= 1 and math.floor(nestedSelector.prob * 100) or nestedSelector.prob * 100)
        end
    end

    if wrapped and (classesRolls or classesProb) then
        result = result .. string.format('{{LinkСard/Сollapsible|name=Группа предметов%s%s|content=', classesRolls or "", classesProb or "")
    end

    result = result .. getTableOutput(nestedSelector.tableId, visited)

    if wrapped and (classesRolls or classesProb) then
        result = result .. "}}"
    end

    return result
end

-- Формирование списка химии
getChemOutput = function(itemData, id)
    local item = findDataById(itemData, id)
    if not item 
       or not item.SolutionContainerManager 
       or not item.SolutionContainerManager.solutions then 
        return ''
    end

    local foodSolution = item.SolutionContainerManager.solutions["food"]
    if not foodSolution or not foodSolution.reagents then 
        return ''
    end

    local result = ""
    for _, reagent in ipairs(foodSolution.reagents) do
        result = result .. string.format(
            '<li>[[Химия#chem_%s|%s]] (%d ед.)</li>',
            reagent.ReagentId, reagent.ReagentId, reagent.Quantity
        )
    end

    return string.format('<ul class="1">%s</ul>', result)
end

-- Основная функция модуля
function p.main(frame)
    local mode = frame.args[1]
    local id = frame.args[2]

    if not id then return 'Не указан ID.' end
    
    local itemDataIndex = itemData
    
    if not itemData then return 'Не удалось загрузить данные.' end

    if mode == 'framing' then
        local subMode = frame.args[2]
        local id = frame.args[3]

        if not id then
            return 'Не указан ID для режима framing.'
        end

        if subMode == 'chem' then
            return frame:preprocess('{{СollapsibleMenu|color=#3e7c82|' .. getChemOutput(chemData, id) .. '}}')
        elseif subMode == 'contained' then
            return frame:preprocess('{{СollapsibleMenu|' .. getContainedOutput(itemDataIndex, id) .. '}}')
		elseif subMode == "slot" then
		    local itemDataEntry = findDataById(itemSlotsData, id)
		    if not itemDataEntry then return "" end
		
		    local startingItem = getFirstStartingItem(itemDataEntry)
		    if not startingItem then return "" end
		
		    return frame:preprocess('{{СollapsibleMenu|color=#71702a|' .. formatContent(startingItem) .. '}}')
        else
            return 'Неизвестный подрежим для framing: ' .. subMode
        end
    elseif mode == 'chem' then
        return frame:preprocess(getChemOutput(chemData, id))
    elseif mode == 'contained' then
        return frame:preprocess(getContainedOutput(itemDataIndex, id))
	elseif mode == "slot" then
	    local itemDataEntry = findDataById(itemSlotsData, id)
	    if not itemDataEntry then return "" end
	
	    local startingItem = getFirstStartingItem(itemDataEntry)
	    if not startingItem then return "" end
	
	    return frame:preprocess(formatContent(startingItem))
    elseif mode == 'rolls' then
        local entity = findDataById(itemDataIndex, id)
        if not entity then return 'ID не найден в данных.' end

        if entity.EntityTableContainerFill then
            local containers = entity.EntityTableContainerFill.containers
            if containers.entity_storage and containers.entity_storage.rolls then
                return processRolls(containers.entity_storage.rolls)
            end
        end

        return ''
    else
        return 'Неизвестный режим: ' .. mode
    end
end

return p