Модуль:Местонахождение

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

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

local p = {}

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

local gearData             = mw.loadData("Модуль:IanComradeBot/startingGear.json/data")
local jobData              = mw.loadData("Модуль:IanComradeBot/job.json/data")
local gearRoleLoadout      = mw.loadData("Модуль:IanComradeBot/roleLoadout.json/data")
local loadoutData          = mw.loadData("Модуль:IanComradeBot/loadout.json/data")
local loadoutGroupData     = mw.loadData("Модуль:IanComradeBot/loadoutGroup.json/data")

local itemBorgData         = mw.loadData("Модуль:IanComradeBot/prototypes/ItemBorgModule.json/data")

local cargoData            = mw.loadData("Модуль:IanComradeBot/prototypes/сargo.json/data")

local latheData            = mw.loadData("Модуль:IanComradeBot/prototypes/lathe.json/data")
local recipeData           = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipes.json/data")
local recipePackData       = mw.loadData("Модуль:IanComradeBot/prototypes/lathe/recipe pack.json/data")
local researchData         = mw.loadData("Модуль:IanComradeBot/prototypes/research.json/data")
local materialData         = mw.loadData("Модуль:IanComradeBot/prototypes/materials.json/data")
local chemDataLathe        = mw.loadData("Модуль:IanComradeBot/chem prototypes.json/data")

local vendingMachinesData  = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines.json/data")
local inventoriesData      = mw.loadData("Модуль:IanComradeBot/prototypes/vending machines/inventories.json/data")

---------------------------------------------------------------------
-- Вспомогательные функции
---------------------------------------------------------------------

-- Обобщённый рекурсивный поиск по полю key с условием predicate
local function searchInStructure(struct, key, predicate)
    if type(struct) ~= "table" then
        return false
    end
    if struct[key] and predicate(struct[key]) then
        return true
    end
    for _, v in pairs(struct) do
        if type(v) == "table" and searchInStructure(v, key, predicate) then
            return true
        end
    end
    return false
end

local function searchItemInStructure(struct, targetId)
    return searchInStructure(struct, "id", function(val) return val == targetId end)
end

local function searchTableIdInStructure(struct, tableIds)
    return searchInStructure(struct, "tableId", function(val)
        for _, tid in ipairs(tableIds) do
            if val == tid then return true end
        end
        return false
    end)
end

-- Формирование ссылки для сущности (используется в reverseContained, reverseLathe, reverseVending)
local function createEntityLink(entityId)
    local nameCode = "{{#invoke:Entity Lookup|getname|" .. entityId .. "}}"
    return "[[" .. nameCode .. "|" .. nameCode .. "]]"
end

-- Формирование ссылки для таблицы грузов (reverseCargo)
local function createCargoLink(storage)
    local nameCode = "{{#invoke:Entity Lookup|getname|" .. storage .. "}}"
    return "[[Таблица грузов#" .. nameCode .. "|" .. nameCode .. "]]"
end

-- Формирование ссылки для роли/джоба (reverseEquipment)
local function createJobLink(jobId)
    local translation = "{{#invoke:Ftl|main|translation|" .. jobId .. "}}"
    return "[[" .. translation .. "|{{ucfirst:" .. translation .. "}}]]"
end

---------------------------------------------------------------------
-- Логика поиска
---------------------------------------------------------------------

local function findRelatedTables(initialList)
    local results = {}
    local function recursiveSearch(tblId)
        if results[tblId] then 
            return 
        end
        results[tblId] = true
        for id, entry in pairs(tableData) do
            if type(entry) == "table" then
                for _, value in pairs(entry) do
                    if type(value) == "table" and value.tableId == tblId then
                        recursiveSearch(id)
                    end
                end
            end
        end
    end
    for _, tblId in ipairs(initialList) do
        recursiveSearch(tblId)
    end
    local res = {}
    for id in pairs(results) do 
        table.insert(res, id)
    end
    return res
end

local function findMatchingStorages(targetId)
    local initialTables = {}
    for key, tblEntry in pairs(tableData) do
        if type(tblEntry) == "table" and searchItemInStructure(tblEntry, targetId) then
            local tableId = tblEntry.id or key
            table.insert(initialTables, tableId)
        end
    end

    local allRelatedTables = (#initialTables > 0) and findRelatedTables(initialTables) or {}

    local matchingStorages = {}
    for storageKey, storage in pairs(itemData) do
        if type(storage) == "table" then
            local found = false
            if storage.EntityTableContainerFill 
               and storage.EntityTableContainerFill.containers then
                if searchTableIdInStructure(storage.EntityTableContainerFill.containers, allRelatedTables) then
                    found = true
                end
            end
            if searchItemInStructure(storage, targetId) then
                found = true
            end
            if found then
                local actualId = storage.id or storageKey
                table.insert(matchingStorages, actualId)
            end
        end
    end

    return matchingStorages
end

---------------------------------------------------------------------
-- Функции обратного поиска
---------------------------------------------------------------------

function p.reverseContained(frame)
    local targetId = frame.args[2]
    if not targetId or targetId == "" then
        return "Ошибка: не указан id предмета для обратного поиска."
    end

    local matchingStorages = findMatchingStorages(targetId)
    local filteredStorages = {}
    for _, sid in ipairs(matchingStorages) do
        local skip = false
        for _, cargo in pairs(cargoData) do
            if type(cargo) == "table" and cargo.product == sid then
                skip = true
                break
            end
        end
        if not skip then
            table.insert(filteredStorages, sid)
        end
    end

    if #filteredStorages == 0 then
        return ""
    end

    local links = {}
    for _, storage in ipairs(filteredStorages) do
        table.insert(links, createEntityLink(storage))
    end

    return table.concat(links, ", ")
end

function p.reverseEquipment(frame)
    local targetId = frame.args[2]
    local slotFilter = frame.args[3]
    if not targetId or targetId == "" then
        return "Ошибка: не указан id оборудования для обратного поиска."
    end

    local results = {}

    -- Обработка startingGear (gearData)
    for _, gear in pairs(gearData) do
        local currentGearId = gear.id or "Unknown"
        if gear.equipment then
            for slot, equipId in pairs(gear.equipment) do
                if equipId == targetId and (not slotFilter or slot == slotFilter) then
                    local foundJob = nil
                    for jobId, job in pairs(jobData) do
                        if job.startingGear == currentGearId then
                            foundJob = jobId
                            break
                        end
                    end
                    if foundJob then
                        table.insert(results, createJobLink(foundJob))
                    end
                end
            end
        end
    end

    -- Обработка loadout (loadoutData)
    for _, loadout in pairs(loadoutData) do
        if loadout.equipment then
            for slot, equipId in pairs(loadout.equipment) do
                if equipId == targetId and (not slotFilter or slot == slotFilter) then
                    local foundGroupId = nil
                    for _, group in pairs(loadoutGroupData) do
                        if group.loadouts and type(group.loadouts) == "table" then
                            for _, lId in ipairs(group.loadouts) do
                                if lId == loadout.id then
                                    foundGroupId = group.id
                                    break
                                end
                            end
                        end
                        if foundGroupId then break end
                    end
                    local foundJob = nil
                    if foundGroupId then
                        for _, role in pairs(gearRoleLoadout) do
                            if role.groups then
                                for _, g in ipairs(role.groups) do
                                    if g == foundGroupId then
                                        foundJob = role.id
                                        break
                                    end
                                end
                            end
                            if foundJob then break end
                        end
                    end
                    if foundJob then
                        table.insert(results, createJobLink(foundJob))
                    end
                end
            end
        end
    end

    if #results == 0 then
        return ""
    end

    return table.concat(results, ", ")
end

function p.reverseCargo(frame)
    local searchValue = frame.args[2]
    if not searchValue or searchValue == "" then
        return "Ошибка: не указано значение для поиска в режиме cargo."
    end

    -- Сначала ищем прямые совпадения по product
    local directCargo = {}
    for _, entry in ipairs(cargoData) do
        if entry.product == searchValue then
            table.insert(directCargo, entry.id)
        end
    end


    if #directCargo > 0 then
		local links = {}
		for _, storage in ipairs(directCargo) do
			table.insert(links, createCargoLink(storage))
		end
		return table.concat(links, ", ")
    end

    -- Если прямых совпадений нет, выполняем обратный поиск среди хранилищ
    local matchingStorages = findMatchingStorages(searchValue)
    local cargoStorages = {}
    for _, sid in ipairs(matchingStorages) do
        for _, cargo in pairs(cargoData) do
            if type(cargo) == "table" and cargo.product == sid then
                table.insert(cargoStorages, sid)
                break
            end
        end
    end

    if #cargoStorages == 0 then
        return ""
    end

    local links = {}
    for _, storage in ipairs(cargoStorages) do
        table.insert(links, createCargoLink(storage))
    end
    return table.concat(links, ", ")
end

local function getRecipeById(recipeId)
    for _, recipe in ipairs(recipeData) do
        if recipe.id == recipeId then
            return recipe
        end
    end
    return nil
end

function p.reverseLathe(frame)
    local targetRecipe = frame.args[2]
    if not targetRecipe or targetRecipe == "" then
        return "Ошибка: не указан результат рецепта для обратного поиска."
    end

    local matchingPacks = {}
    for _, pack in ipairs(recipePackData) do
        if pack.recipes then
            for _, recipe in ipairs(pack.recipes) do
                if recipe == targetRecipe then
                    table.insert(matchingPacks, pack.id)
                    break
                end
            end
        end
    end

    if #matchingPacks == 0 then
        return ""
    end

    local function containsAny(array, targets)
        for _, v in ipairs(array or {}) do
            for _, t in ipairs(targets) do
                if v == t then 
                    return true 
                end
            end
        end
        return false
    end

    local matchingLathes = {}
    for _, lathe in ipairs(latheData) do
        local found = false
        if lathe.Lathe then
            if containsAny(lathe.Lathe.staticPacks, matchingPacks) or containsAny(lathe.Lathe.dynamicPacks, matchingPacks) then
                found = true
            end
        end
        if not found and lathe.EmagLatheRecipes then
            if containsAny(lathe.EmagLatheRecipes.emagStaticRecipes, matchingPacks) or containsAny(lathe.EmagLatheRecipes.emagDynamicPacks, matchingPacks) then
                found = true
            end
        end
        if found and lathe.id then
            table.insert(matchingLathes, lathe.id)
        end
    end

    if #matchingLathes == 0 then
        return ""
    end

    local links = {}
    for _, latheId in ipairs(matchingLathes) do
        table.insert(links, createEntityLink(latheId))
    end

    return table.concat(links, ", ")
end

function p.reverseVending(frame)
    local invMode = frame.args[2] or ""   -- режим: "inventory", "contraband", "emag" или пустая строка для всех
    local targetId = frame.args[3]
    if not targetId or targetId == "" then
        return "Ошибка: не указан id предмета для обратного поиска в торговых автоматах."
    end

    -- Определяем соответствующие ключи для поиска в инвентарях
    local inventoryTypes = {
        inventory   = "startingInventory",
        contraband  = "contrabandInventory",
        emag        = "emaggedInventory"
    }

    local matchingInventoryIds = {}
    for _, inventory in pairs(inventoriesData) do
        if inventory.id then
            local found = false
            if invMode ~= "" then
                local key = inventoryTypes[invMode]
                if key and inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
                    found = true
                end
            else
                for _, key in pairs(inventoryTypes) do
                    if inventory[key] and type(inventory[key]) == "table" and inventory[key][targetId] then
                        found = true
                        break
                    end
                end
            end
            if found then
                table.insert(matchingInventoryIds, inventory.id)
            end
        end
    end

    if #matchingInventoryIds == 0 then
        return ""
    end

    local matchingVendingMachines = {}
    for _, vm in pairs(vendingMachinesData) do
        if vm.VendingMachine and vm.VendingMachine.pack then
            for _, invId in ipairs(matchingInventoryIds) do
                if vm.VendingMachine.pack == invId then
                    if vm.id then
                        table.insert(matchingVendingMachines, vm.id)
                    end
                    break
                end
            end
        end
    end

    if #matchingVendingMachines == 0 then
        return ""
    end

    local links = {}
    for _, vmId in ipairs(matchingVendingMachines) do
        table.insert(links, createEntityLink(vmId))
    end

    return table.concat(links, ", ")
end

function p.reverseBorg(frame)
    local targetItem = frame.args[2]
    if not targetItem or targetItem == "" then
        return "Ошибка: не указан искомый элемент для поиска в ItemBorgModule."
    end

    local results = {}
    -- Проходим по всем записям из itemBorgData
    for _, entry in pairs(itemBorgData) do
        if type(entry) == "table" and entry.ItemBorgModule and type(entry.ItemBorgModule) == "table" then
            local items = entry.ItemBorgModule.items
            if type(items) == "table" then
                for _, item in ipairs(items) do
                    if item == targetItem then
                        table.insert(results, createEntityLink(entry.id))
                        break
                    end
                end
            end
        end
    end

    if #results == 0 then
        return ""
    end

    return table.concat(results, ", ")
end

---------------------------------------------------------------------
-- Основная функция модуля
---------------------------------------------------------------------
function p.main(frame)
    local mode = frame.args[1]
    if not mode or mode == "" then
        return "Ошибка: не указан режим обратного поиска. Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe, reverseVending."
    end

    local modeFunctions = {
        reverseContained = p.reverseContained,
        reverseEquipment = p.reverseEquipment,
        reverseCargo     = p.reverseCargo,
        reverseLathe     = p.reverseLathe,
        reverseVending   = p.reverseVending,
        reverseBorg      = p.reverseBorg,
    }

    if modeFunctions[mode] then
        return mw.getCurrentFrame():preprocess(modeFunctions[mode](frame))
    else
        return "Неизвестный режим: " .. mode .. ". Доступные режимы: reverseContained, reverseEquipment, reverseCargo, reverseLathe, reverseVending."
    end
end

return p