# -*- coding: utf-8 -*-
"""
    MoinMoin - ManageUsers Macro

    Based on functions taken from:
        userform.py
        MoinMoin - UserPreferences Form and User Browser
        @copyright: 2001-2004 by Jürgen Hermann <jh@web.de>

    To use this macro the following procedure (potentially UNSAFE as it makes a link to user file public)
    should be inserted into user.py (somewhere near the def save()):

    def getFilename(self):
        return self.__filename()

    When an account is deleted from Wiki, it's necessary to clean the cache.
    This macro only cleans user cache in current Wiki,
    so if there's a farm, you'll have to clean cache in other Wikies on your own or using another macro.

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

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

import os
import re
from MoinMoin import user, util, wikiutil, caching
from MoinMoin.util.dataset import TupleDataset, Column
from MoinMoin.Page import Page

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

    # do not show system admin to users not in superuser list
    if not request.user.isSuperUser():
        return ''

    # check whether we already have a file name in parameters
    par = request.form.get('useradm', [None])[0]
    if par is not None:
        try:
            os.remove(par)
        except OSError:
            return "error deleting main profile file; stopping"
        try:
            os.remove(par + ".trail")
        except OSError:
            return "error deleting trail; main profile was deleted"

        caching.CacheEntry(request, 'user', 'name2id').remove()
        return "<u>" + par + "</u> has been deleted and the cache <b>IN CURRENT Wiki</b> was cleaned. To clean cache in other Wiki either goto file system or use my CleanUserCache macro."

    # if no file to delete is given then list the users
    data = TupleDataset()
    data.columns = [
        Column('name', label=_('Username')),
        Column('email', label=_('Email')),
        Column('theme', label=_('Theme')),
        Column('action', label=_('Action')),
        Column('filename', label=_('Filename')),
        Column('delete', label=_('Delete')),
    ]

    # Iterate over users
    for uid in user.getUserList(request):
        account = user.User(request, uid)

        userhomepage = Page(request, account.name)
        if userhomepage.exists():
            namelink = userhomepage.link_to(request)
        else:
            namelink = account.name

        data.addRow((
            request.formatter.rawHTML(namelink),
            (request.formatter.url(1, 'mailto:' + account.email, css='mailto', do_escape=0) +
             request.formatter.text(account.email) +
             request.formatter.url(0)),
             request.formatter.text(account.theme_name),
            request.page.link_to(request, text=_('Mail user his account data'),
                                 querystr={"action":"userform",
                                            "email": account.email,
                                            "account_sendmail": "1",
                                            "sysadm": "users"}),
            request.formatter.text(account.id),
            wikiutil.link_tag(request, "%s?useradm=%s" % (macro.formatter.page.page_name, account.getFilename()), "delete"),
        ))

    if data:
        from MoinMoin.widget.browser import DataBrowserWidget

        browser = DataBrowserWidget(request)
        browser.setData(data)
        return browser.toHTML()

    # No data
    return ''

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

