##parameters=REQUEST, cluster=None, cpsdocument_edit_and_view_button=None, came_from=None
# $Id: external_edit.py 805 2006-11-09 09:38:29Z joachim $
"""
Called when a document form is posted.

Validates data, then:

 - if there's no error, updates the object and redirects to it,

 - if there's an error, puts data in session and redirects to edit form.

A form uid is propagated during the redirect to uniquely identify the
form in the session.
"""

from urllib import urlencode
from Products.CPSDocument.utils import getFormUidUrlArg

# Check flexible controls
#context.editLayouts(REQUEST=REQUEST)

# Validate the document and write it if it's valid
# (We don't call getEditableContent here, validate does it when needed.)
doc = context.getContent()
if context.portal_type == "StudentStudyCourse":
    if len(context.objectIds()) > 0:
        psm = 'Edit of StudyCourse is only possible if there are no levels'
        args = getFormUidUrlArg(REQUEST)
        args['portal_status_message'] = psm
        url = context.absolute_url() + '?' + urlencode(args)
        REQUEST.RESPONSE.redirect(url)
        
is_valid, ds = doc.validate(request=REQUEST, proxy=context, cluster=cluster,
                            use_session=True)

##if action is None:
##    ti = doc.getTypeInfo()
##    action = ti.queryMethodID('edit', 'external_edit_form')
##    action = '/' + action

action = "/" + came_from

if is_valid:
    comments = REQUEST.get('comments')
    context.cpsdocument_notify_modification(comments=comments)
    if context.portal_type == "StudentStudyCourse":
        course = ds.get('study_course')
        student_id = context.getStudentId()
        res = context.portal_catalog(portal_type='Certificate',id = course)
        if res:
            c_brain = res[0]
            c_path = c_brain.getPath().split('/')
            student_id = context.getStudentId()
            context.students_catalog.modifyRecord(id = student_id,
                                                  course = course,
                                                  faculty = c_path[-4],
                                                  department = c_path[-3],
                                                  )
    elif context.portal_type in ("StudentPersonal",):
        name = "%(firstname)s %(middlename)s %(lastname)s" % ds
        student_id = context.getStudentId()
        app_doc = context.application.getContent()
        jamb_sex = 'M'
        if ds.get('sex'):
            jamb_sex = 'F'
        app_doc.edit(mapping={'jamb_lastname': name,
                              'jamb_sex': jamb_sex
                              })
        context.students_catalog.modifyRecord(id = student_id,
                                              name = name,
                                              sex = ds.get('sex'),
                                             )
    elif context.portal_type == "Course":
        context.courses_catalog.modifyRecord(**ds)
    if cpsdocument_edit_and_view_button is not None:
        action = ''
    psm = 'psm_content_changed'
    args = {}
else:
    psm = 'psm_content_error'
    args = getFormUidUrlArg(REQUEST)

args['portal_status_message'] = psm
url = context.absolute_url() + action + '?' + urlencode(args)
REQUEST.RESPONSE.redirect(url)

