#format python
"""
MoinMoin macro to create a list of current users
UserList.py
ark  06/13/04  0.1

    ***********
    originally by Antti Kuntsi <antti@kuntsi.com>
    As far as the author is concerned, this code is released to the public
    domain, but some restrictions in the MoinMoin COPYING file may apply. Ask a
    lawyer.
    ***********
    This code has not been tested exhaustively. Use at your own risk.
    The multiple column support has been tested a little
    ***********

    This macro displays a list of currently known users.

    Usage:
        <<UserList2(....)>>
        parameters:
          columncount=INT
          width=PERCENTUAL WIDTH OF BOX
          grouplabel - whether render linkbar with initials


    Changes to suit to API changes of 1.3.x releases done by CyA, (c) 2005-02-28
    Multicolumn layout redesigned by CyA

"""


import string, time, os, getopt
from math import ceil
from MoinMoin import wikiutil, user
from MoinMoin.config import multiconfig

def create_realname(username):
    realname=""

    start=1
    for i in username:
        if start == 0 and i.isupper():
            realname+=" %s" % i
        else:
            realname+=i
        if start == 1:
            start = 0
    return realname

def execute(macro, args):
    '''handle the UserList Macro. return the generated display HTML
    ark  06/13/04'''
    result = []
    columnlist=[]

    # get user from Wiki cache
    users = user.getUserList(macro.request)
    if not users:
      return
    else:
      #get identifications of users
      userlist=[]
      for uid in users:
        name = user.User(macro.request, id=uid).name
        userlist.append(name)
      # create a dictionary with initials as keys and lists of usernames as values
      initials={}
      for u in userlist:
        initial=u[0]
        if not initial in initials.keys():
          initials[initial]=[]
        initials[initial].append(u)

    # define standard values
    rowsize=1
    grouplabel=0
    tablewidth=100

    # parse the arguments
    args = _parse_arguments(args, ',')

    # use passed in options
    if args:
      for o,a in args:
        # how many columns to use in output table
        if o in ("--columncount"):
          rowsize=int(a)

        # label each group of users which is started by new initial by special row
        if o in ("--grouplabel"):
          grouplabel=1

        # use defined table width
        if o in ("--width"):
          # is it not relative?
          if a.find("%") < 0:
            if a<0:
              a=100
            if a>100:
              a=100
            a=a+"%"
          tablewidth=a

    result.append(macro.formatter.rawHTML('<table style="width: %s;">') % tablewidth)
    ik=initials.keys()
    ik.sort()
    for initial in ik:
      users=initials[initial]
      count=len(users)

      rows=ceil(count/float(rowsize)) # how much rows will take group of users with the same initials
      row=0
      col=0
      userindex=0

      if grouplabel == 1:
        result.append(macro.formatter.rawHTML('<tr><td width="100%%" colspan="%s"><a id="%s"><span style="text-transform: uppercase; font-weight: bold;">%s</span></a></td></tr>' %(rowsize,initial,initial)))
      while row < rows:
        result.append(macro.formatter.table_row(1))
        while col < rowsize:
          result.append(macro.formatter.table_cell(1))
          if userindex < count:
            name=users[userindex]
            pagename = macro.formatter.pagelink(1, name)
            realname = create_realname(name)
            content=pagename+realname+"</a>"
          else:
            content="&nbsp;"
          result.append(macro.formatter.rawHTML("%s") % content)
          result.append(macro.formatter.table_cell(0))
          userindex+=1
          col+=1
        col=0
        result.append(macro.formatter.table_row(0))
        row+=1

    result.append(macro.formatter.table(0))

    if grouplabel==1:
      anchorlinks=""
      for a in ik:
        anchor=macro.formatter.anchorlink(1,a)+a+"</a> "
        anchorlinks+=anchor
      anchorlinks=anchorlinks[:-1]
      result.insert(0, anchorlinks)

    result.append(macro.formatter.rawHTML('<br clear="both">'))
    return "\n".join(result)


def _parse_arguments(argstring, delimchar=',', quotechar='"',macro=None,result=None):
    '''
        transform argument string into form suitable for getopt and parse it.
        I'm lazy to finding out original ways when the standard one does exist. cya.
    '''

    if argstring:
      arguments=argstring.split(delimchar)
      args=[]
      for a in arguments:
        a='--'+a
        args.append(a)

      try:
        opts, oargs = getopt.getopt(args, "", ["columncount=","width=","grouplabel"])
      except getopt.GetoptError:
        opts=None
    else:
      opts=None

    return opts