local exports = {}

local function verbData(ending)
   local group
   if ending == 'pôr' or ending == 'por' then
     group = 'er'
   elseif ending == 'erir-defective' then
     group = 'ir'
   else
     group, _ = string.gsub(ending, "%d+$", "")
     group = string.sub(group, #group-1)
   end
   if group == "" then
   	  return nil
   end
   local success, m_verb_data = pcall(require, "Module:pt-conj/data/-"..group)
   if success and m_verb_data[ending] then
      return mw.clone(m_verb_data[ending])
   else
      return nil
   end
end

local function applyFuncToTableValues(tbl, func)
   for k,v in pairs(tbl) do
      if type(v) == 'table' then
         applyFuncToTableValues(v, func)
      else
         tbl[k] = func(v)
      end
   end
end

-- stem (required if applicable): beginning of the verb. All characters of the infinitive form, except those in the template's title.
-- ending (required): Ending of the verb. The last characters chosen specifically by the template.
-- compound (required if applicable): Compound words. Text to be added after the verb.
function exports.inflect(stem, ending, compound)
   local data = verbData(ending)
   if data then
      applyFuncToTableValues(data.forms, function(form)
         if form ~= "" then
            return stem .. form .. (compound and (' ' .. compound) or '')
         else
            return ""
         end
      end)
      return data
   else
      return nil
   end
end


-- The main entry point.
-- This is the only function that can be invoked from a template.
function exports.show(frame)
   local m_table = require("Module:pt-conj/table")
   local args = frame:getParent().args
   local stem, ending, compound = args[1], args[2], args[3]
   local word = exports.inflect(stem, ending, compound)
   if word then
      return m_table.create(word)
   else
      error("No inflection data found")
   end
end

return exports