# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - ManageUsers Macro

    Copyright (c) 2007 by Alexander "Loki" Agibalov
    
    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. 
"""

import os
import re
from MoinMoin import user, util, wikiutil, caching
from MoinMoin.util.dataset import TupleDataset, Column
from MoinMoin.Page import Page


def execute(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 request.formatter.text(par) <> '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 ''
