# -*- coding: iso-8859-1 -*-
"""
                             _vi
                             <Ii           _aa.
                             :I>          aZ2^
                              v`        .we^
        . .         ..        +        _2~
  ._auqXZZX   ._auqXZZZ`    ...._...   ~          ._|ii~
.aXZZY""^~~  vX#Z?""~~~._=ii|+++++++ii=,       _=|+~-
JXXX`       )XXX'    _|i+~   .__..._. +l=    -~-
SXXo        )XZX:   |i>  ._%i>~~+|ii| .i|   ._s_ass,,.    ._a%ssssssss
-SXZ6,,.    )XZX:  =l>  _li+~`   iii| .ii _uZZXX??YZ#Za, uXUX*?!!!!!!!
  "!XZ#ZZZZZXZXZ`  <i>  =i:     .|ii| .l|.dZXr      4XXo.XXXs,.
      -~^^^^^^^`   -||,  +i|=.   |ii| :i>:ZXZ(      ]XZX.-"SXZUZUXoa,,
                     +l|,  ~~|++|++i|||+~:ZXZ(      ]ZZX     ---~"?Z#m
            .__;=-     ~+l|=____.___,    :ZXZ(      ]ZXX_________auXX2
       ._||>+~-        .   -~+~++~~~-    :ZXZ(      ]ZXZZ#######UX*!"
       -+--          .>`      _
                   .<}`       3;
                 .<l>        .Zc
                .ii^         )Xo
                             ]XX

    MoinMoin - gallery2Image Actionmacro

    PURPOSE::
        This action macro is used to update a poll

    CALLING SEQUENCE::
        called by Doodle area with POST

    PROCEDURE::
        Ask adg@crans.org to stop doing drugs

    RESTRICTIONS::
        Written in python

    AUTHOR::
        Antoine Durand-Gasselin <adg@crans.org>
"""

import re, locale, base64
from MoinMoin import wikiutil
from MoinMoin.Page import Page
from MoinMoin.PageEditor import PageEditor

def execute(pagename, request):

    if not request.user.may.write(pagename):
        request.theme.add_msg(_('You are not allowed to edit this page.'), "error")
        Page(request, pagename).send_page()
        return

    raw = Page(request, pagename).body
    pollname = request.form.get("pollname")[0]
    doosearchre = "{{{\s*#!Doodle\s*%s.*?}}}" % re.escape(pollname)
    doosearch = re.search(doosearchre, raw, re.S)
    doos = doosearch.start()
    dooe = doosearch.end()
    if not doosearch:
        request.theme.add_msg(request.getText (u"Le sondage \"%s\" n'a pas été trouvé" % pollname), "error")
        Page(request, pagename).send_page()
        return

    doostring= raw[doos+3:dooe-3]
    doolines = [ l.strip() for l in doostring.splitlines()]
    doodata = filter (lambda x: x != "", doolines)

    fields = filter (lambda x: x != "", [f.strip() for f in doodata[0].split(';')[1:]])

    userl = request.form.get("user")
    if not userl: user = request.user.name
    else:
        if userl[0].strip(): user = userl[0].strip()
        else:  user = request.user.name

    newentry = user + ";"
    for f in fields:
        if isinstance(f, unicode):
            # l'utf-8, c'est bien! On encode l'unicode en utf-8 avant
            # de le base64er
            formfield = base64.encodestring(f.strip().encode('utf-8')).strip('\r\t \n=')
        else:
            # Bon, si on n'a pas un unicode, on encode sauvagement, mais
            # ça peut chier
            formfield = base64.encodestring(f.strip()).strip('\r\t \n=')
        disp = request.form.get(formfield)
        if disp:
            newentry += " %s=%s;" % (f, disp[0])
        else:
            newentry += " %s=%s;" % (f, '0')

    updatepoll = False
    newdoolist = doodata[0:1]
    for participant in doodata[1:]:
        findentry = re.search ("^\s*%s\s*;.*$" % re.escape(user), participant)
        if findentry:
            if updatepoll: pass
            else:
                updatepoll = True
                newdoolist.append(newentry)
        else:
            newdoolist.append(participant)

    if not updatepoll:
        newdoolist.append(newentry)

    newdoostring = "\n".join(newdoolist)

    pg = PageEditor(request, pagename)
    try:
        pg.saveText(raw[:doos+3]+ newdoostring + raw[dooe-3:], 0)
    except:
        request.theme.add_msg(request.getText(u"Aucune modification n'a été effectuée"), "error")

    Page(request, pagename).send_page()
