local p = {}

local allies = require("Module:Reply to/allies")

local function makeError(msg)
  msg ='خطأ [[قالب:رد على]]: ' .. msg
  return mw.text.tag('strong', {['class']='error'}, msg)
end

function p.replyto(frame)
  local origArgs = frame:getParent().args
  local args = {}
  local maxArg = 1
  local usernames = 0
  for k, v in pairs(origArgs) do
    if type(k) == 'number' then
      if mw.ustring.match(v,'%S') then
        if k > maxArg then maxArg = k end
        usernames = usernames + 1
        local title = mw.title.new(v)
        if not title then return makeError('يحتوي الإدخال على رموز محظورة') end
        -- Check for aliases
        local alias = allies[v]
        args[k] = alias or title.rootText
        -- Assign alias to 'label' if available
        if alias then 
            args['label'..tostring(k)] = title.rootText 
        end
      end
    elseif v == '' and k:sub(0,5) == 'لقب' then
      args[k] = '​'
    else
      args[k] = v
    end
  end

  if usernames > (tonumber(frame.args.max) or 50) then
    return makeError(string.format(
      'حُدد أكثر من %s اسماً.',
      tostring(frame.args.max or 50)
    ))
  else
    if usernames < 1 then
      if frame.args.example then args[1] = frame.args.example else return makeError('لم يُحدد اسم المستخدم.') end
    end
    args['label1'] = args['س'] or args['س1'] or args['لقب1'] or args['لقب'] or args['i'] or args['label1'] or args['label']
    
    local outStr = args['prefix'] or args['بادئة'] or '@'
    for i = 1, maxArg do
      if args[i] then
        if  i>1 then outStr = outStr .. ' و' end
        outStr = string.format(
          '%s[[User:%s|%s]]',
          outStr,
          args[i],
          args['label'..tostring(i)] or args['لقب'..tostring(i)] or args['س'..tostring(i)] or args[i]
        )
      end
    end
    outStr = outStr..(args['ت'] or args['p'] or ':')
    return mw.text.tag('span', {['class']='template-ping'}, outStr)
  end
end

return p