Advertisement

Documentation for this module may be created at Module:ItemLink/doc

local p = {}

local Arguments = require('Dev:Arguments')
local DissectDlcItemName = require('Module:DissectDlcItemName')


function p.mainW(f)
	local args = Arguments.getArgs(f, {
		trim = true,
		removeBlanks = true,
	})
	return p.create(args[1] or '1', {
		mod = args.mod,
		link = args.link,
		image = args.image,
		size = args.size,
		text = args.text or args[2],
		quantity = args.quantity,
		noDlcIcon = args.noDlcIcon ~= nil,
	})
end


function p.create(target, args)
	args = args or {}
	
	assert(target ~= nil, 'item link target must not be a null value')
	
	local text = args.text or target
	local linkTarget = args.link or target
	local iconSize = args.size or '20x20px'
	local iconFileName = args.image or (target..'.png')

	if args.mod then
		-- Prefix the link target
		linkTarget = 'Mod:'..args.mod..'/'..linkTarget
		-- Prefix the item icon name if it has not been specified explicitly by the client
		if not args.image then
			iconFileName = 'Mod '..args.mod..' '..iconFileName
		end
	end

	-- Escape characters ":+/" in the icon file name
	iconFileName = iconFileName:gsub('[:%+/]', {
		[":"] = "_",
		["+"] = "-",
		["/"] = "_",
	})

	-- If display text had not been specified explicitly by the caller, try to determine the DLC and strip the text suffix
	local dlcIcon = ''
	if not args.text then
		local dlcResult = DissectDlcItemName.tryMatch(linkTarget)
		if dlcResult ~= nil then
			text = dlcResult.displayName

			-- Construct a DLC icon
			if not args.noDlcIcon then
				dlcIcon = string.format(' [[File:%s|16px|link=%s|alt=(%s)]]',
										dlcResult.dlcIcon, dlcResult.dlcArticle, dlcResult.dlcArticle)
			end
		end
	end

	-- If display text had not been specified explicitly by the caller, retrieve it from the target
	if not args.text then
		local title = mw.title.new(text)
		text = title and title.text or text
	end

	-- Build the final output
	local out = string.format('[[File:%s|%s|class=itemlink|alt=|link=%s]] [[%s|%s]]%s',
							  iconFileName, iconSize, linkTarget, linkTarget, text, dlcIcon)
	if args.quantity then
		out = args.quantity..' × '..out
	end
	return out
end


return p