# -*- coding: utf-8 -*-
"""
    MoinMoin - LostSoulsInGroups macro

    List all items in custom groups that do not have user accounts
    (either haven't registered yet or have been deleted or there's a typo)

    @copyright: 2007 Alexander "Loki" Agibalov
    @license: GNU GPL, see COPYING for details.

    changes:
        12.2007 - conversion to new syntax by Bolesław Kulbabiński
"""

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

def macro_LostSoulsInGroups(macro, args):
    request = macro.request
    _ = macro.request.getText

    sRet = u"<p><b>Éléments dans des groupes custom qui ne correspondent pas à un compte wiki :</b></p>"
    sRet = sRet + u"<table>"
    userlist = []
    lostsouls = {}
    for uid in user.getUserList(request):
        userlist.append(user.User(request, uid).name)

    isgroup = request.cfg.cache.page_group_regex.search
    grouppages = request.rootpage.getPageList(user='', filter=isgroup)

    # Expression matchant un WikiNom
    wikiname_expr = "[^][| ]+"
    # Cas où le wikinom est tout seul
    wikiname_alone = "(?P<wikiname>%s)" % wikiname_expr
    # Cas où il est avec des [[]], éventuellement avec un |
    wikiname_aliased = "\[\[([^|]+\|)?(?P<wikiname2>%s)\]\]" % wikiname_expr
    # Fusion des cas
    wikiname = "(%s|%s)" % (wikiname_alone, wikiname_aliased)
    # Contexte
    srch = "^ \* %s" % wikiname
    srch = re.compile(srch)
    for pg in grouppages:
        pged = PageEditor(request, pg)
        pagelines = pged.getlines()
        for lin in pagelines:
            srchS = srch.match(lin)
            if srchS:
                dic = srchS.groupdict()
                st = dic["wikiname"] or dic["wikiname2"]
                try:
                    usr = userlist.index(st)
                except ValueError:
                    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 = u'<tr><td>%s</td><td>%s</td></tr>' % (Page(request, k).link_to(request), ", ".join(v))
        sRet = sRet + st

    sRet = sRet + "</table>"
    return macro.formatter.rawHTML(sRet)


def execute(macro, args):
    try:
        return wikiutil.invoke_extension_function(
                   macro.request, macro_LostSoulsInGroups, args, [macro])
    except ValueError, err:
        return macro.request.formatter.text(
                   "<<LostSoulsInGroups: %s>>" % err.args[0])

