Documentation for this module may be created at Modulu:wdl-izena/dok

local p = {}

-- Return the first form of the lexeme which has exactly the given grammatical feature.
local function formWithSingleGrammaticalFeature( lexeme, item_id )
	for i, form in pairs( lexeme:getForms() ) do
		local grammaticalFeatures = form:getGrammaticalFeatures()
		if #grammaticalFeatures == 1 and grammaticalFeatures[1] == item_id then
			return form
		end
	end
	return nil
end

-- Return the representation of the form in the given language code,
-- or the first representation otherwise.
local function representationInLanguage( form, language_code )
	local representation, language = form:getRepresentation( language_code )
	if representation then
		return { representation, language }
	else
		return form:getRepresentations()[1]
	end
end

local function termSpan( term )
	local text = term[1]
	local lang = term[2]
	local dir = mw.language.new( lang ):getDir()
	local span = mw.html.create( 'span' )
	span:attr( 'lang', lang )
		:attr( 'dir', dir )
		:wikitext( text )
	return tostring( span )
end

local function singularPlural( lexeme_id, item_id )
	local lexeme = mw.wikibase.getEntity( lexeme_id )
	local form = formWithSingleGrammaticalFeature( lexeme, item_id )
	if form == nil then
		return "''forma hori ez dago''"
	end
	local representation = representationInLanguage( form, 'eu' )
	return termSpan( representation )
end

function p.singular( frame )
	return singularPlural( frame.args[2], 'Q110786', 'Q332734' )
end

function p.plural( frame )
	return singularPlural( frame.args[2], 'Q146786', 'Q332734'  )
end

return p