Module:Infobox officeholder

From Soyjak Wiki, the free ensoyclopedia
Jump to navigationJump to search

local p = {}
local getArgs = require('module:Arguments').getArgs

local fields = { 'office', 'term', 'term_start', 'term_end', 'predecessor', 'successor', 'admin', 'manager' }

local function collect(args)
	local byNum, nums = {}, {}
	for key, value in pairs(args) do
		if type(key) == 'string' and value:find('%S') then
			for _, field in ipairs(fields) do
				local num = key:match('^' .. field .. '(%d*)$')
				if num then
					if not byNum[num] then
						byNum[num] = { num = num }
						table.insert(nums, num)
					end
					byNum[num][field] = value
					break
				end
			end
		end
	end
	table.sort(nums, function(a, b)
		return (tonumber(a) or 0) < (tonumber(b) or 0)
	end)
	local blocks = {}
	for _, num in ipairs(nums) do
		table.insert(blocks, byNum[num])
	end
	return blocks
end

function p._offices(args)
	local offices, orphans = {}, {}
	local current
	for _, block in ipairs(collect(args)) do
		if block.office then
			current = { office = block.office, tenures = { block } }
			table.insert(offices, current)
		elseif current then
			table.insert(current.tenures, block)
		else
			table.insert(orphans, block)
		end
	end
	return offices, orphans
end

function p.offices(frame)
	local infobox = frame.args.infobox
	local out = {}
	for _, block in ipairs(collect(getArgs(frame, { parentOnly = true }))) do
		local args = { infobox = infobox }
		for _, field in ipairs(fields) do
			args[field] = block[field]
		end
		table.insert(out, frame:expandTemplate { title = 'Infobox officeholder/office', args = args })
	end
	return table.concat(out)
end

return p