# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - LostSoulsInGroups macro 
    
    Find users in custom groups who don't have user accounts 
    (either haven't registered yet or have been deleted or there's a typo)
    
    Copyright (c) 2007 by Alexander "Loki" Agibalov

"""

from MoinMoin import wikiutil, user
from MoinMoin.Page import Page
from MoinMoin.PageEditor import PageEditor
import re, sys

def makeStr(lst):
    st=""
    for l in lst:
        if len(st)>1:
            st=st+", "
        st=st+l
    return st

def execute(macro, args):
    request=macro.request
    _=macro.request.getText
    sRet="<p><b>Users in custom groups who don't have user accounts</b></p>"
    sRet=sRet+"<table>"
    userlist=[]
    lostsouls={}
    for uid in user.getUserList(request):
        userlist.append(user.User(request, uid).name)
        
    GrpPages = request.rootpage.getPageList(filter=re.compile("(?!SystemPages|AutoAdmin).*Group$").match)
    srch=re.compile("^ \* [^ ]*", re.M)
    for pg in GrpPages:
        pged = PageEditor(request, pg)
        pagelines = pged.getlines()
        for lin in pagelines:
            srchS=srch.match(lin)
            if srchS:
                st=srchS.group()
                st=st[3:]
                try:
                    usr=userlist.index(st)
                except:
                    if lostsouls.has_key(pg):
                        temp_lst=lostsouls[pg]
                        temp_lst.append(st)
                        lostsouls[pg]=temp_lst
                    else:
                        lostsouls[pg]=[st]
    for k, v in lostsouls.iteritems():
        st='<tr><td>%s</td><td>%s</td></tr>' % (Page(request, k).link_to(request), makeStr(v))
        sRet=sRet+st
    
    sRet=sRet+"</table>"
    
    return macro.formatter.rawHTML(sRet)
