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

require('strict')

local p = {}

local getArgs = require('Module:Arguments').getArgs
local yesno = require('Module:Yesno')

--[=[
Generate a {{DEFAULTSORT}} magic word according to the defaultsort parameter
]=]
function p._construct_defaultsort(args)
	local defsortKey
	local title = mw.title.getCurrentTitle().text
	
	if args.sortkey then
		defsortKey = args.sortkey
	else
		-- construct defaultsort automatically by stripping A/An/The as needed
		local title_table = mw.text.split(title, '/')
		local sorted_title
		local sorted_title_table = {}
		
		local articles = {'A', 'An', 'The'}
		for k, part in pairs(title_table) do
			local sorted_part = part
			local disambig = string.match(sorted_part, ' %(.*%)$')
			if disambig then
				sorted_part = string.gsub(sorted_part, ' %(.*%)$', '')
			else
				disambig = ''
			end
			
			for j, article in pairs(articles) do
				if string.len(sorted_part) > string.len(article) and string.sub(sorted_part, 1, string.len(article) + 1) == (article .. ' ') then
					sorted_part = string.sub(sorted_part, string.len(article) + 2) .. ', ' .. article .. disambig
					break
				end
			end
			table.insert(sorted_title_table, sorted_part .. disambig)
		end
		
		defsortKey = table.concat(sorted_title_table, '/')
		if defsortKey == title then
			defsortKey = nil
		end
	end
	
	-- if a suitable key is found or constructed, apply it
	if defsortKey == title then
		return args.equalsortcat or ''
	elseif defsortKey then
		return mw.getCurrentFrame():callParserFunction('DEFAULTSORT', {defsortKey}) .. (args.diffsortcat or '')
	end
	
	-- otherwise, don't do anything and use the default
	return ''
end

function p.construct_defaultsort(frame)
	return p._construct_defaultsort(getArgs(frame))
end

return p