# -*- coding: iso-8859-1 -*-
"""
    MoinMoin - RecommendPage Action Macro

    PURPOSE:
        This macro is used to recommend a page to an other wiki user.

    Syntax:
        http://localhost:8080/WikiName?action=RecommendPage

    PROCEDURE:
       You get an input mask to enter the username of the one where you like to send the recommendation. This is then stored on a page named WikiName/RecommendedPage as an wiki itemlist with the link and the first five lines in plain text. At the end your user SIG is written.
       A new entry is always written on top of the page. 
       The person is informed by an email notification about the changes

       If you don't enter a name the recommendation is done to your name

       Please remove the version number from the filename.

    MODIFICATION HISTORY:
        @copyright: 2005 by MoinMoin:ReimarBauer
        @license: GNU GPL, see COPYING for details.
        Version: 1.3.4-1

        2005-04-19 : Version 1.3.4-2
                     acl line on top of recommendation is set for a valid user/RecommendedPage to
                     WikiName:admin,read,write,delete All:read,write
                     otherwise for All:read,write
                     If the page user/RecommendedPage already exist acl right given on that page are used.
                     output changed similiar to the search output.

       2005-04-21 : Version 1.3.4-3
                    output changed into calling ShortText()
                    e.g.  * ["RulesForUnzip"]  [[ShortText(RulesForUnzip)]] ... @SIG@
                    it is also checked by now if acls are enabled in the config
       2005-09-02 : Version 1.3.5-4 
                    from SubscribeTo by Raphael Bossek learned to add an subscription for the email notification for a user before the new recommendation is written to the file. This means the user gots informed by an email.                
       2005-09-05 : Version 1.3.5-5
                    isSubscribedTo from user replaced because it could not destinguish between subpage and page
                    my implementation does not understand regular expressions at the moment so this gives by using regular expressions
                    one extraline in the config. 
       2005-09-07 : Version 1.3.5-6
                    text box changed to a selection menu for the user names (sorted by name)     
       2005-09-08 : Version 1.3.5-7
                    bug fix: spaces in html are different in browsers
                             in some browser no selction did not give the user name    
       2005-10-31 : Version 1.3.5-8
                    multiple selection added                                                   
                    no acl rights are set on a new recomendation page acls on an existing recommendation page not overwritten
                    non admin users could use this function too.
                    code changed by a version request to be useable with 1.5.0 too
       2006-02-03 : Version  1.5.1-9 1.3 compatible code removed
                    bug with wrong counted bad user fixed
       2008-01-11 : Version 1.6.0-10 refactored for 1.6 

"""
from MoinMoin import wikiutil, user
from MoinMoin.Page import Page
from MoinMoin.PageEditor import PageEditor

def RecommendPage(request, pagename, username):
    err = None
    name = "%(username)s/RecommendedPage" % {"username": username}
    page = PageEditor(request, name)
    if request.user.may.write(name):
        if user.getUserId(request, username) is not None:
            uid = user.getUserId(request, username)
            recom_user = user.User (request, id=uid)

            subscription_list = recom_user.getSubscriptionList()
            isSubscribedTo = 0
            for test in subscription_list:
                if test == name:
                   isSubsribedTo = 1

            if isSubscribedTo == 0:
                recom_user.subscribe(name)
                recom_user.save()

        newtext = u" * [[%(pagename)s]]  <<ShortText(%(pagename)s)>> ...\n %(username)s\n" % {
                 "pagename": pagename,
                 "username": "@SIG@"}

        if not page.exists():
           PageEditor.saveText(page, newtext, 0)
        else:
            body = page.get_data()
            meta = page.get_meta()
            text_meta = ''
            for command, attrib in meta:
                text_meta = '#%s %s\n%s' % (command, attrib, text_meta)

            text = "%s\n%s\n%s\n" % (text_meta, newtext, body)
            PageEditor.saveText(page, text, 0)
    else:
        err = "Can not write"
        return err

def execute(pagename, request):
    _ = request.getText
    actname = __name__.split('.')[-1]

    if request.user.valid and request.user.may.read(pagename):
        thispage = Page(request, pagename)
        if request.form.has_key('button') and request.form.has_key('ticket'):
            if not wikiutil.checkTicket(request, request.form['ticket'][0]):
                  return thispage.send_page(msg=_('Please use the interactive user interface to recommend pages!'))

            selected_users = request.form.get('username', [u''])
            good = []
            bad = []
            for username in selected_users:
                i = 0
                if len(username.strip()) == 0:
                    username = request.user.name
                    selected_users[i] = username
                    i += 1

                err = RecommendPage(request, pagename, username)
                if err is None:
                   good.append(username)
                else:
                   bad.append(username)

            msg = "recommended to read %(pagename)s to %(username)s" % {
                  "pagename": pagename,
                  "username": ' '.join(good)}

            msg_bad = ''
            if len(bad) > 1:
                msg_bad = "\ncan not recommend page to read to %(username)s" % {
                          "username":' '.join(bad)}

            msg = "%s%s" % (msg, msg_bad)
            request.theme.add_msg(msg, "info")
            thispage.send_page()
            return
        users = user.getUserList(request)
        html = []
        for uid in users:
            name = user.User(request, id=uid).name
            html.append("<OPTION>%(name)s</OPTION>" % {"name":name})

        html.sort()
        n = min([3, len(html)])

        formhtml = '''
<form method="post" >
<strong>%(querytext)s</strong><BR>
<select name="username" size="%(len)s" multiple>
%(option)s
</select>
<input type="hidden" name="action" value="%(actname)s">
<input type="submit" name="button" value="%(button)s">

<BR>
(no selection recommends to: %(user)s)

<input type="hidden" name="ticket" value="%(ticket)s">
<p>
</form>''' % {
    'querytext': 'Recommend page to',
    'actname': 'RecommendPage',
    'ticket': wikiutil.createTicket(request),
    'option': ' '.join(html),
    'user': request.user.name,
    'len': n,
    'button': 'Recommend'}

        request.theme.add_msg(formhtml, "info")
        thispage.send_page()
        return
