Modul:Clothing

Aus Steel Beasts Wiki
Version vom 24. Juni 2023, 17:37 Uhr von sc>FoXFTW
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)

Die Dokumentation für dieses Modul kann unter Modul:Clothing/Doku erstellt werden

local Clothing = {}

local metatable = {}
local methodtable = {}

metatable.__index = methodtable

local objectData = mw.loadData( 'Module:Clothing/Data' )

-- Extensions
local common = require( 'Module:Common' )
local api = require( 'Module:Common/Api' )
local armor = require( 'Module:CharArmor' )
local TNT = require( 'Module:Translate' ):new()
local localized = require( 'Module:Localized' )
local log = require( 'Module:Log' )
local item = require( 'Module:Item' )
local commodity = require( 'Module:Commodity' )


--- Add manual smw data
function methodtable.addManual( self )
    if self.frameArgs == nil then
        return
    end

    local setObj = {
        [ 'Name' ]                                = self.frameArgs.Name                                    or nil,
        [ 'Beschreibung' ]                        = self.frameArgs.Beschreibung                            or nil,
        [ 'Hersteller' ]                          = self.frameArgs[ 'Hersteller' ]                         or nil,
        [ 'Typ' ]                                 = self.frameArgs[ 'Typ' ]                                or nil,
        [ 'Ist Basisversion' ]                    = self.frameArgs[ 'Ist Basisversion' ]                   or nil,
        [ 'Basisversion UUID' ]                   = self.frameArgs[ 'Basisversion UUID' ]                  or nil,
        [ 'SP' ]                                  = self.frameArgs[ 'SP' ]                                 or nil,
        [ 'Temperaturresistenz Minimal' ]         = self.frameArgs[ 'Temperaturresistenz Minimal' ]        or nil,
        [ 'Temperaturresistenz Maximal' ]         = self.frameArgs[ 'Temperaturresistenz Maximal' ]        or nil,
        [ 'Spielversion' ]                        = self.frameArgs[ 'Spielversion' ]                       or nil,
    }

    mw.smw.set( setObj )
end


--- Request Api Data
--- Using current page name
--- @return table
function methodtable.getApiDataForCurrentPage( self )
    local name = self.frameArgs[ 'uuid' ] or self.frameArgs[ 'name' ] or localized.getMainTitle()

    local json = mw.text.jsonDecode( mw.ext.Apiunto.get_raw( 'v2/clothes/' .. name, {
        include = {
            'shops.items',
        },
    } ) )

    api.checkResponseStructure( json, true, false )

    self.apiData = json[ 'data' ]

    return self.apiData
end



--- Queries the SMW Store
--- @return table
function methodtable.getSmwData( self )
    -- Cache multiple calls
    if self.smwData ~= nil then
        return self.smwData
    end

    -- name from args or current page
    local queryName = self.frameArgs[ 'name' ] or localized.getMainTitle()

    local data = mw.smw.ask( {
        '[[' .. queryName .. ']][[Hersteller::+]]',
        '?#-=page',
        '?Name#-=name',
        '?Hersteller#-=manufacturer',
        '?Beschreibung=description', '+lang=' .. common.getLocaleForPage(),
        '?SP=sp',
        '?Typ#-=type', '+lang=' .. common.getLocaleForPage(),
        '?Typ#-=type_de', '+lang=de',
        '?Temperaturresistenz#-n=tempresist',
        '?Länge=length',
        '?Breite=width',
        '?Höhe=height',
        '?Volumen=volume',
        '?Spielversion#-=version',
        'mainlabel=-'
    } )

    if data == nil or data[ 1 ] == nil then
        return TNT.formatInLanguage( self.lang, 'Module:Common/i18n.json', 'msg_smw_loading' )
    end

    self.smwData = data[ 1 ]

    self.smwData.price = commodity.getPrice( queryName )
    if self.smwData.price ~= nil then
        self.smwData.price = self.smwData.price[ 1 ].price
    end

    return self.smwData
end


--- Semantic Properties
--- @return table SMW Result
function methodtable.setSemanticProperties( self )
    -- Api Error, don't set anything
    if self.apiData == nil then
        return
    end
    
    local item = item:new( '', self.apiData )

    local setObj = item:makeSmwObject()

	setObj[ 'Typ' ] = api.mapTranslation( Clothing.translateType( self.apiData.clothing.clothing_type or nil ) )
    setObj[ 'Temperaturresistenz' ] = {
        armor.formatTemperature( self.apiData.clothing.temp_resistance_min ),
        armor.formatTemperature( self.apiData.clothing.temp_resistance_max ),
    }

    local result = mw.smw.set( setObj )

    commodity:new():addShopData( self.apiData )

    return result
end

--- Entrypoint for {{#seo:}}
function methodtable.setSeoData( self )
    if self.currentFrame == nil then
        error( 'No frame set. Call "setFrame" first.', 0 )
    end

    local data = self:getSmwData()

    if nil == data.manufacturer then
        -- Faulty SMW data, don't call #seo
        return
    end

	local manufacturer = require( 'Module:Hersteller' )

    local code = manufacturer.getCodeFromName( data.manufacturer )
    if code == data.manufacturer then
    	code = ''
	end

    require( 'Module:SEO' ).set(
        'Kleidung',
        data.page,
        table.concat({
            data.name,
            data.manufacturer,
            self.currentFrame:preprocess( '{{SITENAME}}' )
        }, ' - '),
        'replace',
        {
            data.name,
            data.type,
            data.manufacturer,
            code,
        },
        nil,
        self.frameArgs[ 'image' ],
        data.page
    )
end

--- Creates the infobox
function methodtable.getInfoBox( self )
    local data = self:getSmwData()

	if type( data ) == 'string' then
		return log.info( data )
	end

	local manufacturer = require( 'Module:Hersteller' )

    if nil == data.manufacturer then
        data.manufacturer = TNT.formatInLanguage( self.lang, 'Module:Common/i18n.json', 'unknown_manufacturer' )
    end

    local code = manufacturer.getCodeFromName( data.manufacturer )
    if code == data.manufacturer then
    	code = ''
	else
		code = string.format( ' (%s)', code )
	end

    -- Set Title
    common.setDisplayTitle( self.currentFrame, data.name )

    local box = require( 'Module:InfoboxNeue' ):new( {
        removeEmpty = true,
        emptyString = '-',
        placeholderImage = 'Platzhalter Rüstung.webp',
    } )

	local nameNormalized, _ = mw.ustring.gsub( data.name, "[^%w-]", ' ' )
	nameNormalized, _ = mw.ustring.gsub( nameNormalized, "%s+", ' ' )

    box:renderImage( common.getImage( {
        self.frameArgs[ 'image' ],
        nameNormalized .. '.jpg',
    } ) )

    box:renderHeader( {
    	title = data.name,
    	subtitle = '[[' .. data.manufacturer .. ']]' .. code .. api.getVersionInfoRef( data.version, self.lang )
    } )

    local tempMinRes, tempMaxRes = Clothing.temperatureResistanceToText( data.tempresist )

    local clothingType = data.type
    if clothingType ~= nil then
        clothingType = string.format('[[:Kategorie:%s|%s]]', data.type_de , clothingType)
    end

	box:renderSection( {
		col = 2,
		content = {
    		box:renderItem( TNT.formatInLanguage( self.lang, 'Module:Common/i18n.json', 'lbl_type' ), clothingType or '-' ),
    		box:renderItem( TNT.formatInLanguage( self.lang, 'Module:Common/i18n.json', 'lbl_price' ), data.price or TNT.formatInLanguage( self.lang, 'Module:Common/i18n.json', 'txt_cant_buy' ) ),
    		box:renderItem( TNT.formatInLanguage( self.lang, 'Module:Common/i18n.json', 'lbl_carrying_capacity' ), data.sp or '-' ),
    		box:renderItem( TNT.formatInLanguage( self.lang, 'Module:Common/i18n.json', 'lbl_weight' ), data.volume or '-' ),
		}
	} )


	box:renderSection( {
		title = TNT.formatInLanguage( self.lang, 'Module:CharArmor/i18n.json', 'lbl_temperature_resistance' ),
		col = 2,
		content = {
    		box:renderItem( TNT.formatInLanguage( self.lang, 'Module:CharArmor/i18n.json', 'lbl_temperature_resistance_min' ), tempMinRes or '-' ),
    		box:renderItem( TNT.formatInLanguage( self.lang, 'Module:CharArmor/i18n.json', 'lbl_temperature_resistance_max' ), tempMaxRes or '-' ),
		}
	} )

    return tostring( box )
end


--- Set the frame and load args
--- @param frame table
function methodtable.setFrame( self, frame )
    self.currentFrame = frame
    self.frameArgs = require( 'Module:Arguments' ).getArgs( frame )

    if type( self.frameArgs[ 'Bild' ] ) == 'string' then
    	self.frameArgs[ 'image' ] = self.frameArgs[ 'Bild' ]
	end
end


--- Get categories
function methodtable.getCategories( self )
    return tostring( table.concat( self.categories ) )
end


--- Sets the main categories for this object
function methodtable.setCategories( self, smwData )
	if smwData.manufacturer == nil then
		table.insert( self.categories, '[[Category:Seiten mit Skriptfehlern]]' )
		return
	end

	if self.lang == 'de' then
	    table.insert( self.categories, '[[Category:' .. smwData.manufacturer .. '|' .. smwData.name .. ' ]]' )
	
	    if smwData.type_de ~= nil and smwData.type_de ~= 'Unbekannter Typ' then
	        table.insert( self.categories, string.format('[[Kategorie:%s|%s]]', smwData.type_de, smwData.name ) )
	    else
	    	table.insert( self.categories, string.format('[[Kategorie:Kleidung|%s]]', smwData.name ) )
	    end
    else
    	table.insert( self.categories, string.format('[[Kategorie:%s]]', smwData.name ) )
    end
end


--- Save Api Data to SMW store
function methodtable.saveApiData( self )
    if self.currentFrame == nil then
        error( 'No frame set. Call "setFrame" first.', 0 )
    end

    local data = self:getApiDataForCurrentPage()

    self:setSemanticProperties()

    return data
end


--[[

Clothing Methods

]]--

--- @param type string
--- @return table
function Clothing.translateType( type )
    return {
        de_DE = objectData.typeTranslations[ type ] or type,
        en_EN = type,
    }
end


--- Returns temperature resistances as strings containing °C
--- @param resTable table containing an arbitrary amount of temperatures
--- @return string, string
function Clothing.temperatureResistanceToText( resTable )
    local tempMinRes = math.huge
    local tempMaxRes = -math.huge

    if resTable ~= nil and type( resTable ) == 'table' then
        for _, res in pairs( resTable ) do
            res = common.toNumber( res, 0 )

            if res < tempMinRes then
                tempMinRes = res
            end

            if res > tempMaxRes then
                tempMaxRes = res
            end
        end
    end

    if tempMinRes == math.huge then
        tempMinRes = '-'
    else
        tempMinRes = tempMinRes .. '°C'
    end

    if tempMaxRes == -math.huge then
        tempMaxRes = '-'
    else
        tempMaxRes = tempMaxRes .. '°C'
    end

    return tempMinRes, tempMaxRes
end


--- Template entry
function Clothing.main( frame )
    local instance = Clothing:new()
    instance:setFrame( frame )

	if not localized.isLanguagePage() then
	    if instance.frameArgs[ 'Manuell' ] ~= nil then
	        instance:addManual()
	    else
	        instance:saveApiData()
	    end
	end

	instance:setCategories( instance:getSmwData() )

    instance:setSeoData()

    return tostring( instance:getInfoBox() ) .. instance:getCategories()
end


--- New Instance
function Clothing.new( self, name )
    local instance = {
        categories = {},
        frameArgs = {
            [ 'name' ] = name
        },
        lang = require( 'Module:Template translation' )._getLanguageSubpage( mw.title.getCurrentTitle() )
    }

    setmetatable( instance, metatable )

    return instance
end

return Clothing