Documentation for this module may be created at Module:Main/sandbox/doc

-- Single utility module. Break this into separate modules if it gets too large.

local p = {} -- p stands for package

-- Given an array of titles, check them in order and return the first page which exists
function p.fallback_pages( list )
	for key, value in ipairs( list ) do
		local p = mw.title.new( value )
		if p.exists then
			return p
		end
	end
end

function p.get_appeal( frame )

    local appeal_name = string.gsub( frame.args.appeal , 'Appeal%-', '' )
    local language = frame.args.language
    local country = frame.args.country
    
    local page = p.fallback_pages({
    	'Template:Appeal/' .. appeal_name .. '/' .. language .. '/' .. country,
		'Template:Appeal/' .. appeal_name .. '/' .. language,
		'Template:Appeal/' .. appeal_name .. '/en',
		'Template:Appeal/default/' .. language,
		'Template:Appeal/default/en'
    })

    local expanded = frame:expandTemplate{ title = page, args = frame.args }
    return expanded

end

function p.get_infobox( frame )

    local infobox_name = frame.args.infobox
    local language = frame.args.language
    local country = frame.args.country
    
    local page = p.fallback_pages({
    	'Template:Infobox/' .. infobox_name .. '/' .. language .. '/' .. country,
		'Template:Infobox/' .. infobox_name .. '/' .. language,
		'Template:Infobox/' .. infobox_name .. '/en',
		'Template:Infobox/Default/' .. language,
		'Template:Infobox/Default/en'
    })

    local expanded = frame:expandTemplate{ title = page, args = frame.args }
    return expanded

end

function p.get_tax_message( frame )

    local tax_message = frame.args.tax_message
    local language = frame.args.language
    local country = frame.args.country
    local page

    if ( country == 'US' ) then
        page = mw.title.new( 'Template:Tax/LinkOnly' )
    else
    	page = p.fallback_pages({
    		'Template:Tax/' .. tax_message .. '/' .. language, -- custom message
			'Template:Tax/' .. country .. '/' .. language, -- special countries e.g. FR/NL
			'Template:Tax/Default/' .. language,
			'Template:Tax/LinkOnly'
    	})
    end

    local expanded = frame:expandTemplate{ title = page, args = frame.args }
    return expanded
    
end

function p.page_language( frame )

    local full_title = mw.title.getCurrentTitle().prefixedText
    local t = mw.text.split( full_title, '/' )
    local lang = t[#t]

    if mw.language.isKnownLanguageTag( lang ) then
        return lang
    else
        return 'en'
    end

end

return p