« Module:Utils » : différence entre les versions

De Eco - Wiki Français
Aller à :navigation, rechercher
[version non vérifiée][version vérifiée]
Page créée avec « local p = {} --- Trims and parses the args into a table, then returns the table -- @author User:Avaren function p.normaliseArgs(frame) local origArgs = frame:getParent().args local args = {} for k, v in pairs(origArgs) do v = mw.text.trim(tostring(v)) if v ~= '' then args[k] = v end end return args end --- Get path to icon file. -- @author User:Avaren function p.checkImage(name, too_expensive) local icon = name:gsub('%s+', '') .. '_Icon.png' i... »
 
Aucun résumé des modifications
 
(13 versions intermédiaires par 2 utilisateurs non affichées)
Ligne 2 : Ligne 2 :


--- Trims and parses the args into a table, then returns the table
--- Trims and parses the args into a table, then returns the table
-- @author User:Avaren
function p.normalise(args)
 
for k, v in pairs(args) do
v = mw.text.trim(tostring(v))
if v ~= '' then
args[k] = v
end
end
 
return args
end
 
--- Trims and parses the args into a table, then returns the table
--- @author User:Avaren
function p.normaliseArgs(frame)
function p.normaliseArgs(frame)
local origArgs = frame:getParent().args
local origArgs = frame:getParent().args
Ligne 17 : Ligne 30 :
end
end


--- Get path to icon file.
function p.CheckId(name)
-- @author User:Avaren
local itemData = mw.loadData("Module:ItemData")
function p.checkImage(name, too_expensive)
    local ItemName = p.ItemSearch(name)  
local icon = name:gsub('%s+', '') .. '_Icon.png'
    local itemTable = itemData.items[ItemName]
if too_expensive then
    if itemTable == nil then return 'NoItem' end
return icon
    local IconName = itemTable.ID
end
 
return IconName
if mw.title.makeTitle('File', icon).file.exists then
return icon
else
return 'NoImage.png'
end
end
 
--- Check if <code>item</code> is in given <code>array</code>.
-- @param item Item to look for
-- @param #table array Table to check
-- @return #bool <code>true</code> if <code>item</code> is in <code>array</code>
-- @author User:Avaren
local function in_array(item, array)
-- Should only use on short arrays
local set = {}
for _, l in ipairs(array) do
set[l] = true
end
return set[item] ~= nil
end
end


--- Build HTML code for an icon image.
function p.CheckList(List)
-- @param name string
local NewList = ""
-- @param size string|nil One of: <code>"iconNormal"</code> (64px) or <code>"iconRecipe"</code> (44px). Default: <code>"iconNormal"</code>
if (List ~= "") then
-- @param bg string|nil
local TempList ={}
-- @param border string|nil
for Name in string.gmatch(List, "([^,]+)") do
-- @param too_expensive boolean|nil
TempList[Name] = Name
-- @author User:Avaren
function p.build_icon(name, link, size, bg, border, too_expensive)
local L = require('Module:Localization') -- local import
 
if not size then
size = 'iconNormal'
end
local icon_bg
if bg then
icon_bg = bg
end
local icon_border
if border then
icon_border = border
end
 
local item_data = mw.loadData('Module:ItemData')
local item = item_data.items[name]
local image
if item then
if item['group'] == L.t('Skill Books') then
image = 'SkillBook.png'
icon_bg = 'iconGold'
elseif item['group'] == L.t('Skill Scrolls') then
image = 'Skill Scroll'
icon_bg = 'iconGold'
-- Attempt to generate skill page
elseif in_array(L.t('Basic Research'), item['tagGroups']) then
image = string.sub(item['untranslated'], 1, -7):gsub('%s+', '') .. '_Icon.png'
icon_bg = 'paperBasic'
elseif in_array(L.t('Advanced Research'), item['tagGroups']) then
image = string.sub(item['untranslated'], 1, -10):gsub('%s+', '') .. '_Icon.png'
icon_bg = 'paperAdvanced'
elseif in_array(L.t('Modern Research'), item['tagGroups']) then
image = string.sub(item['untranslated'], 1, -8):gsub('%s+', '') .. '_Icon.png'
icon_bg = 'paperModern'
else
image = p.checkImage(item['untranslated'], too_expensive)
end
end
if not icon_bg then
if item['group'] == L.t('Food') then
for Name,Data in pairs(TempList) do
icon_bg = 'iconGreen'
if (NewList == "") then NewList = NewList .. Name else NewList = NewList .. "," .. Name end
elseif item['carried'] == L.t('Hands') then
icon_bg = 'iconBrown'
end
end
end
else
image = p.checkImage(name, too_expensive)
end
end
return NewList
end


if not icon_bg then
function p.getLanguageCode()
icon_bg = 'iconBlue'
  local language = mw.language.getContentLanguage()
end
  local languageCode = language:getCode()
  return languageCode
end


if border then
function p.getLanguageName()
icon_border = border
  local languageName = "English"
else
  local language = mw.language.getContentLanguage()
icon_border = 'borderBlue'
  local languageCode = language:getCode()
end
  if languageCode == "ru" then languageName = "Russian" end
  if languageCode == "de" then languageName = "German" end
  if languageCode == "fr" then languageName = "French" end
  return languageName
end


if size == 'iconNormal' then
function p.checkImage(filename)
icon_container = 'iconContainer'
if filename then
else
if mw.title.makeTitle('Media', filename).file.exists then return "Y" else return "N" end
icon_container = 'iconContainerSmall'
else return "Error name" end
end
end


if not link then
function p.checkPage(pagename)
link = ''
local pagetitle = mw.title.new(pagename)
else
if pagetitle and pagetitle.exists then return "Y" else return "N" end
link = '|link='..link
end
end


local file = '[[File:' .. image .. '|frameless|class=' .. size .. ' ' .. icon_bg .. link ..']]'
return '<div class="' .. icon_container .. '"><div class="iconStack">' .. file .. '</div><div class="iconBorder ' .. icon_border .. '" style="position:absolute;"></div></div>'
end


--- Get HTML code for an icon image.
function p.SkillSearch(PageName)
-- @author User:Avaren
local SkillName = ''
function p.Icon(frame)
local skillData = require( "Module:SkillData" )
args = p.normaliseArgs(frame)
    local skillList = skillData.skills
return p.build_icon(args.name, args.link, args.size, args.bg, args.border, args.too_expensive)
    local Lang = p.getLanguageName()
    for Sname,Sdata in pairs(skillList) do
    if (Sdata.Name[Lang] == PageName) then SkillName = Sname end
    end
    return SkillName
end
end


--- Calculate the length of a table by iterating over every item in it.
function p.SkillSearchByID(SkillID)
--
local SkillName = 'None'
-- <code>mw.LoadData</code> prevents <code>#tbl</code> from working correctly.
local skillData = require( "Module:SkillData" )
-- @param #table tbl Table to calculate the length of
    local skillList = skillData.skills
-- @return #number Length of the table.
    local Lang = p.getLanguageName()
-- @author User:Avaren
    for Sname,Sdata in pairs(skillList) do
function p.tableLen(tbl)
    if (Sdata.SkillID == SkillID) then SkillName = Sname end
local count = 0
    end
for _, v in ipairs(tbl) do
return SkillName
if v == nil then
return count
end
count = count + 1
end
return count
end
end


--- Check if <code>value</code> is not <code>nil</code> and return it or if it is <code>nil</code> fall back to <code>default</code>.
-- Normalise les apostrophes typographiques en apostrophes droites
-- @param value Value to check
function p.NormalizeApostrophes(text)
-- @param default Value to fall back to
    if text == nil then return text end
-- @return <code>value</code> if it is not <code>nil</code>
    -- Remplace les apostrophes typographiques ' et ' par l'apostrophe droite '
-- @return <code>default</code> if <code>value</code> is <code>nil</code>
    return text:gsub("'", "'"):gsub("'", "'")
-- @author User:Demian
-- @see valueOrDash
-- @see formatNilToYesNo
-- @see formatBoolToYesNo
function p.valueOrDefault(value, default)
return nil == value and default or value
end
end


--- Check if <code>value</code> is not <code>nil</code> and return it or if it is <code>nil</code> fall back to the em-dash ().
function p.ItemSearch(PageName)
--
    local ItemName = 'None'
-- The em-dash (—) is commonly used represent a missing, not applicable (N/A), or a negative ("no") value with just a single character.
    local ItemData = require("Module:ItemData")
-- @param value Value to check
    local ItemList = ItemData.items
-- @return <code>value</code> if it is not <code>nil</code>
    local Lang = p.getLanguageName()
-- @return #string "—" if <code>value</code> is <code>nil</code>
   
-- @author User:Demian
    -- Normaliser les apostrophes dans le nom de la page
-- @see valueOrDefault
    local NormalizedPageName = p.NormalizeApostrophes(PageName)
function p.valueOrDash(value)
   
return nil == value and "—" or value
    for Iname, Idata in pairs(ItemList) do
        -- Normaliser aussi les apostrophes dans les données
        local NormalizedItemName = p.NormalizeApostrophes(Idata.Name[Lang])
        if (NormalizedItemName == NormalizedPageName) then
            ItemName = Iname
            break
        end
    end
   
    return ItemName
end
end


--- Check if <code>value</code> is not <code>nil</code> and return "Yes" or "No".
function p.ItemNameFromID(itemID)
-- @param value Value to check
    local ItemData = require("Module:ItemData")
-- @return #string "Yes" if <code>value</code> is not <code>nil</code>
    local Lang = p.getLanguageName()
-- @return #string "No" if <code>value</code> is <code>nil</code>
   
-- @author User:Demian
    for key, data in pairs(ItemData.items) do
-- @see valueOrDefault
        if data.ID == itemID then
-- @usage formatNilToYesNo("Hello") == "Yes"
            -- prend la langue courante si elle existe et n'est pas vide
-- @usage formatNilToYesNo(nil) == "No"
            local name = data.Name[Lang]
function p.formatNilToYesNo(value)
            if name == nil or name == "" then
-- TODO: Support i18n.
                name = data.Name["English"]
return nil == value and "No" or "Yes"
            end
            return name or itemID -- fallback sur ID si tout échoue
        end
    end
    return itemID -- fallback si ID inconnu
end
end


--- Check if <code>value</code> <em>evaluates</em> as <code>true</code> and return "Yes" or "No".
function p.TagSearch(PageName)
-- @param value Value to evaluate. Does not have to be a bool.
local TagName = 'None'
-- @return #string "Yes" if <code>value</code> evaluates as <code>true</code>
local TagData = require( "Module:TagData" )
-- @return #string "No" if <code>value</code> evaluates as <code>false</code>
    local TagList = TagData.tags
-- @author User:Demian
    local Lang = p.getLanguageName()
-- @see valueOrDefault
    for Tname,Tdata in pairs(TagList) do
-- @usage formatBoolToYesNo("") == true
    if (Tdata.Name[Lang] == PageName) then TagName = Tname end
-- @usage formatBoolToYesNo(123) == true
    end
-- @usage formatBoolToYesNo(nil) == false
    return TagName
function p.formatBoolToYesNo(value)
-- TODO: Support i18n.
return value and "Yes" or "No"
end
end


--- Format the input values into a string representing the range between the values.
function p.BiomeSearch(PageName)
--
local BiomeName = 'None'
-- Returning an an empty string intended to ease concatenation with other strings.
local BiomeData = require( "Module:BiomeData" )
-- The en-dash (–) (instead of the hyphen-minus "-") is the appropriate character to signify a range of values.
    local BiomeList = BiomeData.biomes
-- @param #number min Minimum value (left side)
    local Lang = p.getLanguageName()
-- @param #number max Maximum value (right side)
    for Bname,Bdata in pairs(BiomeList) do
-- @param #number default Default value in case of an error (only value).
    if (Bdata.Name[Lang] == PageName) then BiomeName = Bname end
-- @param #string valueFormat Format string used with <code>mw.ustring.format</code>.
    end
-- @return #string "<code>min</code>–<code>max</code>" if <code>min < max</code>
    return BiomeName   
-- @return #string "<code>default</code>" formatted with <code>valueFormat</code> if <code>min == max</code> or <code>min > max</code> and <code>default ~= nil</code>
-- @return #string "" (empty string) if either <code>min</code> <strong>or</strong> <code>max</code> do not convert to a numerical value
-- @return #nil <code>nil</code> if <code>min == max</code> or <code>min > max</code> and <code>default == nil</code>
-- @author User:Demian
function p.toRangeString(min, max, default, valueFormat)
min = tonumber(p.valueOrDefault(min, nil))
max = tonumber(p.valueOrDefault(max, nil))
default = tonumber(p.valueOrDefault(default, nil))
 
if nil ~= min and nil ~= max then
if min < max then
return mw.ustring.format(mw.ustring.format("%s–%s", valueFormat, valueFormat), min, max)
elseif nil == default then
return nil
else
return mw.ustring.format(valueFormat, default)
end
end
 
return ""
end
end


--- Get all keys from <code>tbl</code> and sort them in alphabetical order.
function p.AnimalSearch(PageName)
-- @param #table tbl Table to get keys from
local AnimalName = 'None'
-- @return #table Input table keys in alphabetical order.
local AnimalData = require( "Module:AnimalData" )
-- @author User:Demian
    local AnimalList = AnimalData.animals
-- @see getSortedValues
    local Lang = p.getLanguageName()
function p.getSortedKeys(tbl)
    for Aname,Adata in pairs(AnimalList) do
local sorted = {}
    if (Adata.Name[Lang] == PageName) then AnimalName = Aname end
 
    end
for key in pairs(tbl) do
    return AnimalName
table.insert(sorted, key)
end
 
table.sort(sorted)
 
return sorted
end
end


--- Get all values from <code>tbl</code> and sort them in alphabetical order.
function p.SpecialtyXP(Tier)
-- @param #table tbl Table to get values from
local WikiText = ''
-- @return #table Input table values in alphabetical order.
WikiText =  WikiText ..'<table class="table table-striped table-bordered"><tr class="thead-dark"><th>Specialty Level</th><th>2</th><th>3</th><th>4</th><th>5</th><th>6</th><th>7</th></tr><tr><td>Specialty XP</td>'
-- @author User:Demian
for i = 1, 6 do
-- @see getSortedKeys
local XP = Tier * ( 25 * i) ^ 2
function p.getSortedValues(tbl)
WikiText =  WikiText .. '<td>' .. XP .. '</td>'
local sorted = {}
 
for _, value in ipairs(tbl) do
table.insert(sorted, value)
end
end
 
WikiText =  WikiText ..'</tr></table>'
table.sort(sorted)
    return WikiText
 
return sorted
end
end


--- Split <code>str</code> by the given character.
function p.Translate(String)
-- @param #string str String to split
local Translate = String
-- @param #string separator String that separates values in <code>str</code>. May optionally be surrounded by 1 <em>whitespace</em> character by default.
local Lang = p.getLanguageName()
-- @return #table Table of strings that were split from <code>str</code>.
local TranslateData = require( "Module:LocalizationData" )
-- @author User:Demian
local TranslateList = TranslateData.locales
-- @usage splitString("hello, world", ",") == {"hello", "world"}
for Tname,Tdata in pairs(TranslateList) do
function p.splitString(str, separator)
    if ( Tname == String) then Translate = Tdata.Translate[Lang] end
local tbl = {}
    end
 
for token in mw.ustring.gmatch(str, mw.ustring.format("%%s?([^%s]+)%%s?", separator)) do
return Translate
table.insert(tbl, token)
end
 
return tbl
end
end


--- Sort items in the given list of values <code>str</code> separated with <code>separator</code> and return them as a single string.
function p.ItemTags(TagsList)
-- @param #string str String with values separated by <code>separator</code>
local WikiText = ""
-- @param #string separator String that separates values in <code>str</code>
local WikiTagText = ""
-- @param #string joiner String used to join sorted values from <code>str</code>.
local Lang = p.getLanguageName()
-- @return #string <code>str</code> with items sorted in alphabetical order.
local TagString = p.Translate("{0} Tag");
-- @author User:Demian
local TagData = require( "Module:TagData" )
-- @usage sortListString("Dog,Ape, Cat", ",", ";") == "Ape;Cat;Dog"
local IconUtils = require('Module:IconUtils')
function p.sortListString(str, separator, joiner)
for Count,Tname in pairs(TagsList) do
-- Split string by commas.
TagName = TagData.tags[Tname];
-- Sort items.
TagNameLoc = TagName.Name[Lang];
-- Rejoin into string.
TagLink = p.VarSub(TagString,TagNameLoc);
return table.concat(p.getSortedValues(p.splitString(str, separator)), joiner)
if (TagName.IsVisibleInTooltip == "True") then WikiTagText = IconUtils.main{ name = TagNameLoc, id = TagName.ID, size = 128, style = 4, link = TagLink } end
end
if (WikiTagText ~= "") then WikiText = '<div class="row">' .. WikiTagText .. '</div>' end
return WikiText
end
end


--- Check if a page with the title "<code>name</code> (<code>disambiguationTitle</code>)" exists in the database and return that page title, otherwise return "<code>name</code>".
-- variable substitution
--
function p.VarSub(String,Loc)
-- Use sparingly as this uses a comparatively slow MediaWiki function p.to check if a page exists.
return string.gsub(String,'{0}',Loc)
--
-- Using this function p.will create a new entry in the <code>Special:WantedPages</code> list.
-- Be careful when calling this function p.and do not pass garbage into its parameters so you do not clog up that list.
-- This is a long-standing issue with MediaWiki that has not yet been solved, and may not be possible to solve without an architectural change to the software.
-- @param #string name Name of a page.
-- @param #string disambiguationTitle Disambiguation clarifier in a page title.
-- @return #string "<code>name</code> (<code>disambiguationTitle</code>)"
-- @return #string "<code>name</code>"
-- @author User:Demian
function p.getDirectPageName(name, disambiguationTitle)
-- Try to get the actual end page instead of the disambiguation page if it exists.
-- E.g. Salmon has "Salmon (animal)" and "Salmon (item)" as well as the "Salmon" disambiguation page between these two.
local directPage = mw.ustring.format("%s (%s)", name, disambiguationTitle)
return mw.title.new(directPage).exists and directPage or name
end
end


--- Create a wikilink with [[square brackets]] from parameters.
function p.VSTranslate(String,Loc)
-- @param #string pageName The actual name of a page to create a link to
return p.VarSub(p.Translate(String),Loc)
-- @param #string displayText Text to display as a clickable link instead of the page name. If <code>nil</code>, <code>pageName</code> is displayed instead.
-- @param #bool twoLineDisplayText Force the <em>last word</em> of <code>displayText</code> on the next line
-- @return #string "[[<code>name</code>|<code>displayText</code>]]" if <code>displayText</code> is not <code>nil</code>
-- @return #string "[[<code>name</code>]]" if <code>displayText</code> is <code>nil</code> or the same string as <code>name</code>
-- @author User:Demian
function p.formatWikilink(pageName, displayText, twoLineDisplayText)
local finalDisplayText = p.valueOrDefault(displayText, pageName)
 
if twoLineDisplayText then
local lastSpaceIdx = mw.ustring.find(finalDisplayText, " [^ ]*$")
 
if nil ~= lastSpaceIdx then
finalDisplayText = mw.ustring.format("%s<br>%s", mw.ustring.sub(finalDisplayText, 0, lastSpaceIdx-1), mw.ustring.sub(finalDisplayText, lastSpaceIdx+1))
end
end
 
if pageName == finalDisplayText then
return mw.ustring.format("[[%s]]", pageName)
else
return mw.ustring.format("[[%s|%s]]", pageName, finalDisplayText)
end
end
end


--- Add thousands separator to given number and use custom decimal point.
function p.gallery(context)
--
local gallery = frame:callParserFunction{ name = '#tag:gallery', args = { mode = 'slideshow', widths = '100%', ''.. context:getParent().args[1] .. '' , showthumbnails = 'true'} }
-- Extension:NumberFormat is more extensive, but more cumbersome to use and also not installed at the moment.
return gallery
-- @param #string number Number to format. Is processed as a string regardless of type.
-- @param #string thousandsSeparator String to place between each set of 3 digits. Default: " "
-- @param #string decimalPoint String to place between the whole and fractional part of the number. Default: "."
-- @return #string <code>number</code> with the specified thousands separator and decimal point.
-- @return #string <code>number</code> unchanged if it contained 1 or more characters that are <strong>not</strong> a: digit, one of ".,-", a space.
-- @author User:Demian
-- @usage formatNumber(-1234567.89) = "-1 234 567.89"
-- @usage formatNumber("1234567,89", ".", "_") = "1,234,567_89"
function p.formatNumber(number, thousandsSeparator, decimalPoint)
-- Default separator to space.
if nil == thousandsSeparator then
thousandsSeparator = " "
end
 
-- Default point to period.
if nil == decimalPoint then
decimalPoint = "."
end
 
-- We're dealing with formatting a string here.
local numberString = tostring(number)
 
-- Check if the input number is reasonable.
-- Does NOT check for multiple instance of each character.
-- E.g. Inputting something like 123-456.789 will lead to incorrect results.
-- I can't handle every edge case: garbage in, garbage out.
-- The user has to have some responsibility in inputting reasonable numbers.
if mw.ustring.find(numberString, "[^%d%.%-, ]") then
return number
end
 
-- Split input into parts.
-- 1st group: MAY start with a "-".
-- 2nd group: MUST contain 1 or more digits-
-- 3rd group: MAY start with with one of ".,"
-- 3rd group: MAY have 0 or more digits.
local _, _, minus, digits, fraction = mw.ustring.find(tostring(numberString), "(-?)(%d+)([%.,]?%d*)")
 
-- Reverse the string of digits.
-- Append the thousands separator after (before when reversed again) each set of 3 digits.
digits = mw.ustring.gsub(string.reverse(digits), "(%d%d%d)", mw.ustring.format("%%1%s", thousandsSeparator))
 
-- Replace the existing decimal separator with the specified one.
if "" ~= fraction then
fraction = mw.ustring.format("%s%s",decimalPoint, mw.ustring.sub(fraction, 2))
end
 
-- Reverse the string of digits back to the original direction.
-- If the string digits starts with the thousands separator, remove the separator.
-- Add the optional minus in front and the optional fractional part at the back.
-- Need to remember to escape the thousandsSeparator, it could be "." which would translate to "any character"!
return mw.ustring.format("%s%s%s", minus, mw.ustring.gsub(string.reverse(digits), mw.ustring.format("^%%s", thousandsSeparator), ""), fraction)
end
end


--- Check if the string is empty or <code>nil</code>.
function p.FoodsShelfLife(ShelfLife)
-- @param #string str String to check
local WikiText = tonumber(ShelfLife)/86400 .. ' days'
-- @return #bool <code>true</code> if <code>str</code> is <code>nil</code> or an empty string ("").
return WikiText
-- @author User:Demian
function p.isEmpty(str)
return nil == str or "" == str
end
end


return p
return p

Dernière version du 8 mars 2026 à 13:47

Ce module fournit des fonctions utilitaires utilisées par d'autres modules.

Utilisation

Ajoutez la ligne de code suivante en haut de votre fichier :

local Utils = require("Module:Utils")

-- Vous pouvez ensuite appeler les fonctions de ce module dans votre script. Par exemple :
local tableLength = Utils.tableLen(maTable)

local p = {}

--- Trims and parses the args into a table, then returns the table
function p.normalise(args)

	for k, v in pairs(args) do
		v = mw.text.trim(tostring(v))
		if v ~= '' then
			args[k] = v
		end
	end

	return args
end

--- Trims and parses the args into a table, then returns the table
--- @author User:Avaren
function p.normaliseArgs(frame)
	local origArgs = frame:getParent().args
	local args = {}

	for k, v in pairs(origArgs) do
		v = mw.text.trim(tostring(v))
		if v ~= '' then
			args[k] = v
		end
	end

	return args
end

function p.CheckId(name)
	local itemData = mw.loadData("Module:ItemData")
    local ItemName = p.ItemSearch(name) 
    local itemTable = itemData.items[ItemName]
    if itemTable == nil then return 'NoItem' end
    local IconName = itemTable.ID
	
	return IconName
end

function p.CheckList(List)
	local NewList = ""
	if (List ~= "") then
		local TempList ={}
		for Name in string.gmatch(List, "([^,]+)") do
			TempList[Name] = Name
		end
		
		for Name,Data in pairs(TempList) do
			if (NewList == "") then NewList = NewList .. Name else NewList = NewList .. "," .. Name end
		end
	end
	
	return NewList
end

function p.getLanguageCode()
  local language = mw.language.getContentLanguage()
  local languageCode = language:getCode()
  return languageCode
end

function p.getLanguageName()
  local languageName = "English"
  local	language = mw.language.getContentLanguage()
  local languageCode = language:getCode()
  if languageCode == "ru" then languageName = "Russian" end
  if languageCode == "de" then languageName = "German" end
  if languageCode == "fr" then languageName = "French" end
  return languageName
end

function p.checkImage(filename)
	if filename then
		if mw.title.makeTitle('Media', filename).file.exists then return "Y" else return "N" end
	else return "Error name" end
end

function p.checkPage(pagename)
	local pagetitle = mw.title.new(pagename)
	if pagetitle and pagetitle.exists then return "Y" else return "N" end
end


function p.SkillSearch(PageName)
	local SkillName = ''
	local skillData = require( "Module:SkillData" )
    local skillList = skillData.skills
    local Lang = p.getLanguageName()
    	for Sname,Sdata in pairs(skillList) do
    		if (Sdata.Name[Lang] == PageName) then SkillName = Sname end
    	end
    return SkillName
end

function p.SkillSearchByID(SkillID)
	local SkillName = 'None'
	local skillData = require( "Module:SkillData" )
    local skillList = skillData.skills
    local Lang = p.getLanguageName()
    	for Sname,Sdata in pairs(skillList) do
    		if (Sdata.SkillID == SkillID) then SkillName = Sname end
    	end
	return SkillName
end

-- Normalise les apostrophes typographiques en apostrophes droites
function p.NormalizeApostrophes(text)
    if text == nil then return text end
    -- Remplace les apostrophes typographiques ' et ' par l'apostrophe droite '
    return text:gsub("'", "'"):gsub("'", "'")
end

function p.ItemSearch(PageName)
    local ItemName = 'None'
    local ItemData = require("Module:ItemData")
    local ItemList = ItemData.items
    local Lang = p.getLanguageName()
    
    -- Normaliser les apostrophes dans le nom de la page
    local NormalizedPageName = p.NormalizeApostrophes(PageName)
    
    for Iname, Idata in pairs(ItemList) do
        -- Normaliser aussi les apostrophes dans les données
        local NormalizedItemName = p.NormalizeApostrophes(Idata.Name[Lang])
        if (NormalizedItemName == NormalizedPageName) then 
            ItemName = Iname 
            break
        end
    end
    
    return ItemName
end

function p.ItemNameFromID(itemID)
    local ItemData = require("Module:ItemData")
    local Lang = p.getLanguageName()
    
    for key, data in pairs(ItemData.items) do
        if data.ID == itemID then
            -- prend la langue courante si elle existe et n'est pas vide
            local name = data.Name[Lang]
            if name == nil or name == "" then
                name = data.Name["English"]
            end
            return name or itemID -- fallback sur ID si tout échoue
        end
    end
    return itemID -- fallback si ID inconnu
end

function p.TagSearch(PageName)
	local TagName = 'None'
	local TagData = require( "Module:TagData" )
    local TagList = TagData.tags
    local Lang = p.getLanguageName()
    	for Tname,Tdata in pairs(TagList) do
    		if (Tdata.Name[Lang] == PageName) then TagName = Tname end
    	end
    return TagName
end

function p.BiomeSearch(PageName)
	local BiomeName = 'None'
	local BiomeData = require( "Module:BiomeData" )
    local BiomeList = BiomeData.biomes
    local Lang = p.getLanguageName()
    	for Bname,Bdata in pairs(BiomeList) do
    		if (Bdata.Name[Lang] == PageName) then BiomeName = Bname end
    	end
    return BiomeName    
end

function p.AnimalSearch(PageName)
	local AnimalName = 'None'
	local AnimalData = require( "Module:AnimalData" )
    local AnimalList = AnimalData.animals
    local Lang = p.getLanguageName()
    	for Aname,Adata in pairs(AnimalList) do
    		if (Adata.Name[Lang] == PageName) then AnimalName = Aname end
    	end
    return AnimalName
end

function p.SpecialtyXP(Tier)
	local WikiText =  ''
	WikiText =  WikiText ..'<table class="table table-striped table-bordered"><tr class="thead-dark"><th>Specialty Level</th><th>2</th><th>3</th><th>4</th><th>5</th><th>6</th><th>7</th></tr><tr><td>Specialty XP</td>'
	for i = 1, 6 do
		local XP = Tier * ( 25 * i) ^ 2
		WikiText =  WikiText .. '<td>' .. XP .. '</td>'
	end
	WikiText =  WikiText ..'</tr></table>'
    return WikiText
end

function p.Translate(String)
	local Translate = String
	local Lang = p.getLanguageName()
	local TranslateData = require( "Module:LocalizationData" )
	local TranslateList = TranslateData.locales
		for Tname,Tdata in pairs(TranslateList) do
    		if ( Tname == String) then Translate = Tdata.Translate[Lang] end
    	end
	
	return Translate
end

function p.ItemTags(TagsList)
	local WikiText = ""
	local WikiTagText = ""
	local Lang = p.getLanguageName()
	local TagString = p.Translate("{0} Tag");
	local TagData = require( "Module:TagData" )
	local IconUtils = require('Module:IconUtils')
		for Count,Tname in pairs(TagsList) do
			TagName = TagData.tags[Tname];
			TagNameLoc = TagName.Name[Lang];
			TagLink = p.VarSub(TagString,TagNameLoc);
			if (TagName.IsVisibleInTooltip == "True") then WikiTagText = IconUtils.main{ name = TagNameLoc, id = TagName.ID, size = 128, style = 4, link = TagLink } end
		end
	if (WikiTagText ~= "") then WikiText = '<div class="row">' .. WikiTagText .. '</div>' end
	return WikiText
end

-- variable substitution
function p.VarSub(String,Loc)
	return string.gsub(String,'{0}',Loc)
end

function p.VSTranslate(String,Loc)
	return p.VarSub(p.Translate(String),Loc)
end

function p.gallery(context)
	local gallery = frame:callParserFunction{ name = '#tag:gallery', args = { mode = 'slideshow', widths = '100%', ''.. context:getParent().args[1] .. '' , showthumbnails = 'true'} }
	return gallery
end

function p.FoodsShelfLife(ShelfLife)
	local WikiText = tonumber(ShelfLife)/86400 .. ' days'
	return WikiText
end

return p