Hopp til innhold

Modul:SignatureList

Fra Wikipedia, den frie encyklopedi

local lib = {}

function exist( a, b )
	if not(a) then
		return true
	end

	if b == '' or type(b) == 'nil' then
		return false
	end

	return true
end

function getLabel( id, languageCode )
	local label = nil

	if languageCode then
		label = mw.wikibase.getLabelByLang( id, languageCode)
	else
		label = mw.wikibase.getLabel( id )
	end

	return label or ''
end

function getDescription( id, languageCode )
	local description = nil

	if languageCode then
		description = mw.wikibase.getDescriptionByLang( id, languageCode)
	else
		description = mw.wikibase.getDescription( id )
	end

	return description
end

function lib:parts( entityId, propertyId, languageCode, mustHaveLabel, mustHaveDescription, mustHaveSitelink )
	local parts = {}
	local statements = {}

	if entityId then
		statements = mw.wikibase.getBestStatements( entityId, propertyId )
	end
	
	mustHaveLabel = type( mustHaveLabel ) == 'boolean' and mustHaveLabel or false
	mustHaveDescription = type( mustHaveDescription ) == 'boolean' and mustHaveDescription or false
	mustHaveSitelink = type( mustHaveSitelink ) == 'boolean' and mustHaveSitelink or false

	for i,claim in ipairs( statements ) do
		local mainsnak = claim.mainsnak

		if mainsnak.snaktype == 'value' and mainsnak.datatype == 'wikibase-item' then
			local datavalue = mainsnak.datavalue

			if datavalue.type == 'wikibase-entityid' then
				local value = datavalue.value

				if value['entity-type'] == 'item' then
					local id = value.id

					local sitelink = mw.wikibase.getSitelink( id )
					local label = getLabel( id, languageCode )
					local description = getDescription( id, languageCode )

					if exist( mustHaveLabel, label )
						and exist( mustHaveDescription, description )
						and exist( mustHaveSitelink, sitelink ) then
						table.insert( parts, { id, label, description, sitelink } )
					end
				end
			end
		end
	end

	return parts
end

setmetatable( lib, {
	__call = function( self, entityId, propertyId, languageCode, mustHaveLabel, mustHaveDescription, mustHaveSitelink )
		entityId = entityId or mw.wikibase.getEntityIdForCurrentPage()
		local parts = self:parts( entityId, propertyId, nil, nil, nil, nil )
		table.sort( parts, function( a, b ) return mw.ustring.upper( a[2] ) < mw.ustring.upper( b[2] ) end)
		
		local indexes = {}
		for i,part in ipairs( parts ) do
			indexes[part[1]] = i
		end
		
		return parts, indexes
	end })

return lib