Модуль:Prototypes/Машина/Станок

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

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

local p = {}

-- Функция для загрузки данных станков
local function loadLatheData()
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe.json"):getContent())
end

-- Функция для загрузки данных рецептов
local function loadRecipeData()
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/lathe/recipes.json"):getContent())
end

-- Функция для загрузки данных исследований
local function loadResearchData()
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/research.json"):getContent())
end

-- Функция для загрузки данных материалов
local function loadMaterialData()
    return mw.text.jsonDecode(mw.title.new("User:IanComradeBot/prototypes/materials.json"):getContent())
end

-- Функция для форматирования времени
local function format_seconds_to_short_string(input_seconds)
    local minutes = math.floor(input_seconds / 60)
    local seconds = input_seconds % 60

    local minutes_part = minutes > 0 and (minutes .. " мин.") or nil
    local seconds_part = seconds > 0 and (seconds .. " сек.") or nil

    if minutes_part and seconds_part then
        return minutes_part .. " " .. seconds_part
    elseif seconds_part then
        return seconds_part
    elseif minutes_part then
        return minutes_part
    else
        return '0 сек.'
    end
end

-- Функция для сортировки рецептов
local function sortRecipesByPriority(recipes)
    table.sort(recipes, function(a, b)
        local priority = { Static = 1, Unknown = 2, EMAG = 4 }
        local aPriority = priority[a.discipline] or 3
        local bPriority = priority[b.discipline] or 3

        if a.isEmag ~= b.isEmag then
            return not a.isEmag
        end

        if aPriority == bPriority then
            if a.tier == b.tier then
                return a.discipline < b.discipline
            end
            return a.tier < b.tier
        end

        return aPriority < bPriority
    end)
end

function p.main(frame)
	-- Подключение CSS
	local cssLink = frame:extensionTag('templatestyles', '', {
		src = 'Шаблон:Prototypes/Машина/Станок/styles.css'
	})
	
    local latheId = frame.args[1] or ""
    if latheId == "" then
        return '<div style="color:red;">Не указан ID станка.</div>'
    end

    local latheData = loadLatheData()
    local recipeData = loadRecipeData()
    local researchData = loadResearchData()
    local materialData = loadMaterialData()

    local lathe = nil
    for _, data in ipairs(latheData) do
        if data.id == latheId then
            lathe = data
            break
        end
    end

    if not lathe then
        return '<div style="color:red;">Станок с ID "' .. latheId .. '" не найден.</div>'
    end

    local materialMapping = {}
    for _, material in ipairs(materialData) do
        materialMapping[material.material.id] = material.material.stackEntity
    end

    local out = cssLink
    local recipes = {}

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

    local function findInResearch(recipeId)
        for _, research in ipairs(researchData) do
            if research.technology and research.technology.recipeUnlocks then
                for _, unlock in ipairs(research.technology.recipeUnlocks) do
                    if unlock == recipeId then
                        return {
                            name = research.technology.name,
                            tier = research.technology.tier,
                            discipline = research.technology.discipline
                        }
                    end
                end
            end
        end
        return nil
    end

    -- Обработка staticRecipes
	if lathe.Lathe.staticRecipes then
	    for _, recipeId in ipairs(lathe.Lathe.staticRecipes) do
	        local recipe = getRecipeDetails(recipeId)
	        if recipe and recipe.result then
	            table.insert(recipes, {
	                result = recipe.result,
	                completetime = recipe.completetime,
	                materials = recipe.materials,
	                discipline = "Static",
	                tier = 0
	            })
	        else
	            out = out .. '<div style="color:red;">Ошибка: Рецепт с ID "' .. recipeId .. '" не найден или поле result отсутствует.</div>'
	        end
	    end
	end

    -- Обработка dynamicRecipes
    if lathe.Lathe.dynamicRecipes then
        for _, recipeId in ipairs(lathe.Lathe.dynamicRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                local researchInfo = findInResearch(recipeId)
                if researchInfo then
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = researchInfo.discipline,
                        tier = researchInfo.tier,
                        researchName = researchInfo.name
                    })
                else
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = "Unknown",
                        tier = 0
                    })
                end
            end
        end
    end
    
    	
    -- Обработка emagStaticRecipes
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagStaticRecipes then
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagStaticRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                table.insert(recipes, {
                    result = recipe.result,
                    completetime = recipe.completetime,
                    materials = recipe.materials,
                    discipline = "Static",
                    tier = 0,
                    isEmag = true
                })
            end
        end
    end
    
    -- Обработка emagDynamicRecipes 
    if lathe.EmagLatheRecipes and lathe.EmagLatheRecipes.emagDynamicRecipes then
        for _, recipeId in ipairs(lathe.EmagLatheRecipes.emagDynamicRecipes) do
            local recipe = getRecipeDetails(recipeId)
            if recipe then
                local researchInfo = findInResearch(recipeId)
                if researchInfo then
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = researchInfo.discipline,
                        tier = researchInfo.tier,
                        researchName = researchInfo.name,
                        isEmag = true
                    })
                else
                    table.insert(recipes, {
                        result = recipe.result,
                        completetime = recipe.completetime,
                        materials = recipe.materials,
                        discipline = "Unknown",
                        tier = 0,
                        isEmag = true
                    })
                end
            end
        end
    end

    sortRecipesByPriority(recipes)

	-- Таблица для перевода названий дисциплин
	local disciplineMapping = {
	    Arsenal = "Арсенал",
	    Industrial = "Промышленность",
	    Experimental = "Экспериментальное",
	    CivilianServices = "Обслуживание персонала"
	}
	
	-- Таблица для цветов по уровням
	local tierColors = {
	    [1] = "#54d554",
	    [2] = "#ed9000",
	    [3] = "#d72a2a"
	}
	
    for _, recipe in ipairs(recipes) do
        out = out .. '{{Шаблон:Prototypes/Машина/Станок|product=' .. recipe.result
        out = out .. '|complete-time=' .. format_seconds_to_short_string(recipe.completetime)
        out = out .. '|materials='

        if next(recipe.materials) then
            for material, amount in pairs(recipe.materials) do
                local stackEntity = materialMapping[material] or material
                local scaledAmount = amount / 100
                out = out .. '<b>[[File:' .. stackEntity .. '.png|32x32px|link=]] ' .. scaledAmount .. ' {{#invoke:Entity Lookup|getname|' .. stackEntity .. '}}</b>'
            end
        else
            out = out .. 'Нет данных о материалах'
        end
        
        -- Информация об исследовании
        if recipe.discipline ~= "Static" and recipe.discipline ~= "Unknown" then
        	local tierColor = tierColors[recipe.tier] or "#FFFFFF"
        	local disciplineName = disciplineMapping[recipe.discipline] or "Неизвестная дисциплина"
        	
            out = out .. '|info=<div style="font-weight:600;">[[File:' .. recipe.discipline .. '.png|16x16px|link=]] [[Руководство по исследованию и разработке|' .. disciplineName
            out = out .. ']], уровень: <span style="color: ' .. tierColor .. '">' .. recipe.tier .. '</span> </div>'
        end
        
        -- При взломе EMAG
        if recipe.isEmag then
            out = out .. '|mode-emag=1'
        end
        
		-- Информация об иконках
		local icon = ""
		if recipe.isEmag and recipe.discipline ~= "Static" and recipe.discipline ~= "Unknown" then
		    icon = '[[File:JobIconResearchDirector.png|24px|link=Руководство по исследованию и разработке]] <span class="станок__progression-symbol">↓</span> [[File:Emag.png|32px|link=Взламываемые криптографическим секвенсором предметы]]'
		elseif recipe.isEmag then
		    icon = '[[File:Emag.png|32px|link=Взламываемые криптографическим секвенсором предметы]]'
		elseif recipe.discipline ~= "Static" and recipe.discipline ~= "Unknown" then
		    icon = '[[File:JobIconResearchDirector.png|24px|link=Руководство по исследованию и разработке]]'
		end
		
		out = out .. '|icons=' .. icon

		out = out .. '}}'
    end

    return mw.getCurrentFrame():preprocess(out)
end

return p