Modul:Sportskategorier

require('Modul:No globals')
local p = {}

local categories = {}

local addTrackingCategory = function(cat)
	if cat == 'More than one member category' then
		categories[#categories + 1] = '[[Kategori:Sportshold har mere end en medlemskategori angivet på Wikidata]]'
	end
end

p.sportskategorier = function(frame)
	local args = (frame == mw.getCurrentFrame()) and frame:getParent().args or frame.args
	local qid = args.q ~= '' and args.q or mw.wikibase.getEntityIdForCurrentPage()
	if not qid then
		return
	end
	local teams = mw.wikibase.getAllStatements(qid, 'P54') -- P54 is 'member of sports team'
	for _, team in pairs(teams) do
		if team.mainsnak.snaktype == 'value' then
			local teamID = team.mainsnak.datavalue.value.id
			local cats = mw.wikibase.getBestStatements(teamID, 'P6112') -- P6112 is 'category for members of a team'
			local catID = nil
			for _, cat in pairs(cats) do
				if cat.mainsnak.snaktype == 'value' then
					if catID then
						-- If already set, this is a duplicate category.
						addTrackingCategory('More than one member category')
					end
					catID = cat.mainsnak.datavalue.value.id
					local catLink = mw.wikibase.getSitelink(catID)
					if catLink then
						categories[#categories + 1] = '[[' .. catLink .. ']]'
					end
				end
			end
		end
	end
	if args.test == 'ja' then
		-- Line breaks between categories. Add colons to links, and discard second return value from gsub
		return (string.gsub(table.concat(categories, '<br/>'), '%[%[', '[[:'))
	else
		return table.concat(categories)
	end
end

return p