
"""
This file is part of PeerTool, a web application for collaborative
decision-making (Copyrighted, 2009-2010, Ellis & Grant, Inc.)
Developed by Michael F. Ellis <michael.f.ellis@gmail.com>.  
License: AGPL v3
PeerTool comes with ABSOLUTELY NO WARRANTY.
"""                
@auth.requires_login()
def index():
    """ Please describe."""
    debug("Entering ...")

    ## Uncomment if this function will be called
    ## by redirection with a new choice of problem.

    #if request.args and request.args[0] != None:
    #    session.problemid = int(request.args[0])

    problem = loadProblem(session.problemid)
    if problem==None:
        redirect(URL(r=request, c='choose', f='index'))

    dbi = db.invitations                        # shorter name
    form,invrows,editable = invitationform(problem)    
    if form.accepts(request.vars, session):
        session.flash = T('Form accepted.')
        #import pdb; pdb.set_trace()
        deliver = False
        for k,v in form.vars.iteritems():
            debug("")
            if k.startswith('I'):
                ## It's either an email address or it's None.
                debug("key=%(k)s, email=%(v)s"%locals())
                iid = int(k[1:])
                if v != None:
                    debug("Checking for duplicate invitation.")
                    v=v.strip()
                    rows = db((dbi.problemid == session.problemid) &
                              (dbi.email==v)).select()
                    assert len(rows) <= 1
                    if len(rows)==0:
                        debug("Updating the invitation.")
                        db(dbi.id==iid).update(email=v)
                    else:
                        debug("Ignoring duplicate or unchanged invitation.")
                else:
                    debug("Deleting invitation")
                    db(dbi.id==iid).delete()
            elif k=="new_invitation":
                debug("key=%(k)s, email=%(v)s"%locals())
                if v != None:
                    try:
                        checkInvitationLimits()
                    except InvitationLimitException:
                        session.flash = T("Exceeded maximum invitations "\
                        "for this problem!")
                        redirect(URL(r=request, c='default', f='index'))
                        
                    dbi.insert(email=v, 
                        problemid=session.problemid,
                        invitedby=auth.user.email)

            elif k=="deliver":
                debug("key=%(k)s, v=%(v)s"%locals())
                if v==True:
                    debug("Scheduling delivery.")
                    deliver = True              # defer so all other items 
                                                # are processed first
        
        if deliver:
            debug("Delivering invitations")
            db(db.problems.id==session.problemid).update(isembryo=False)

        redirect(URL(r=request, f='index'))
        ## Process submitted data here

        ## Optionally redirect to another page
        #redirect(URL(r=request, f='someinvitation'))

    elif form.errors:
        response.flash = T('Form has errors!')

    else:
        response.flash = T('Fill out the form')
    debug("Leaving ...")    
    return dict(form=form, problem=problem, 
        invrows=invrows, editable=editable)  


def invitationform(problem):
    dbi = db.invitations                        # shorter name
    fields = []
    fields.append(Field("Title",'string',
                   writable=False,
                   readable=True,
                   default=problem.getLabel(),
                   ))

    ## Field for inviting new team members
    fields.append(Field("new_invitation", 'string', 
                    length=100,
                    requires=IS_NULL_OR(IS_EMAIL()),
                    default=None, 
                    ))
    ## Fields for editing existing invitations 
    r = db(db.problems.id==session.problemid).select()
    editable = r[0]['isembryo']                 # can't edit invitations 
                                                # after problem is 'delivered'
    rows = db(dbi.problemid==session.problemid).select()
    for r in rows:
        iid = 'I%(id)s'%r  ## e.g. 'I13'
        fields.append(Field(iid,'string',
                   writable=True if editable else False,
                   readable=True,
                   default=r.email,
                   requires=IS_NULL_OR(IS_EMAIL()),
                   ))
    if editable:
        fields.append(Field("deliver", 'boolean',
                  label="Deliver",
                  default=False,
                  comment=T("Check the box to "\
                    "issue invitations and "\
                    "disable edits on existing "\
                    "items in problem."),                       
                  ))

    form = SQLFORM.factory(*fields)
    return form, rows, editable
