Moduuli:Cs:Wikidata/Formatters/wikibase-entityid

Wikipediasta
Siirry navigaatioon Siirry hakuun

require 'Module:No globals'

local p = {}

local lib = require 'Module:cs:Wikidata/lib'

-- @const
local default_langs = { 'fi', 'en', 'sv', 'de', 'no', 'ru', 'se', 'fr', 'et', 'es' }

local function constructLink(label, link, lang)
	if link then
		if label then
			if lang and lang ~= 'cs' then
				return mw.ustring.format('<span lang="%s">[[%s|%s]]</span>', lang, link, label)
			else
				return '[[' .. link .. '|' .. label .. ']]'
			end
		else
			return '[[' .. link .. ']]'
		end
	end
	if label then
		if lang and lang ~= 'cs' then
			return mw.ustring.format('<span lang="%s">%s</span>', lang, label)
		else
			return label
		end
	end
	return nil
end

function p.getLinkWhenNonexistingLabel(entityId)
	local i18n = mw.loadData('Module:cs:Wikidata/i18n')
	local ImageFormatter = require 'Module:cs:ImageFormatter'
	return ImageFormatter.makeImage('Wikidata-edit.svg', {
		description = i18n['missing-label'],
		link = 'd:' .. entityId,
		size = '27x17px'
	}) .. '<code>[[d:' .. entityId .. '|' .. entityId .. ']]</code>' .. lib.category('missing-label')
end

-- @deprecated
function p.formatEntityWithGender(value, options)
	options.label = 'gender'
	return p.formatValue(value, options)
end

local function getLabel(entityId, options)
	local label, lang
	local Module = require 'Module:cs:Wikidata'
	--if options.label and lib.isPropertyId(options.label) then
	if options.label == 'short' then
		label = Module.formatStatementsFromLua{
			id = entityId,
			limit = 1,
			property = 'P1813',
			rank = 'valid',
			sort = {'rank'},
			withlang = {'cs', 'mul'}
		}
	elseif options.label == 'gender' then
		local gender = Module.getRawValueFromLua{
			entity = options.entity,
			property = 'P21'
		}
		if gender == 'Q6581072' then
			label, lang = Module.formatStatementsFromLua{
				id = entityId,
				limit = 1,
				property = 'P2521',
				rank = 'valid',
				sort = {'rank'},
				withlang = 'cs'
			}, 'cs'
		end
	elseif options.label == 'unitsymbol' then
		label = Module.getRawValueFromLua{
			id = entityId,
			property = 'P558'
		}
	end
	if not label then
		label, lang = lib.getLabelInLanguage(entityId, options.withlang or default_langs)
	end
	return label, lang
end

local function getSitelink(entityId, options)
	if not lib.IsOptionTrue(options, 'nolink') then
		return mw.wikibase.sitelink(entityId)
	end
	return nil
end

function p.formatEntityId(entityId, options)
	local options = options or {}
	local label, lang = getLabel(entityId, options)
	local link = getSitelink(entityId, options)
	return constructLink(label, link, lang) or p.getLinkWhenNonexistingLabel(entityId)
end

function p.getRawValue(value, options)
	if lib.IsOptionTrue(options or {}, 'numeric') then
		return value['numeric-id']
	end
	return value.id
end

p.formatRawValue = p.formatEntityId

function p.formatValue(value, options)
	return p.formatEntityId(p.getRawValue(value, {}), options)
end

return p