##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
if 'ajax_edit' in REQUEST.form:
    return context.waeup_edit_ajax(REQUEST, cluster=cluster)

import logging
logger = logging.getLogger('Skins.waeup_edit')

mtool = context.portal_membership
member = mtool.getAuthenticatedMember()

# 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 StudentStudyCourse is only possible if there are no levels inside!'
        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)

student_id = context.getStudentId()

##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 False:
        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,
                                                      level = ds.get('current_level'),
                                                      verdict = ds.get('current_verdict'),
                                                      faculty = c_path[-4],
                                                      department = c_path[-3],
                                                      )
                logger.info('%s edited %s (%s) of %s' % (member,context.id,course,student_id))

        elif context.portal_type == "StudentApplication": # disabled
            entry_mode = ds.get('entry_mode')
            #student_id = context.getStudentId()
            context.students_catalog.modifyRecord(id = student_id,
                                                  entry_mode = entry_mode,
                                                 )
            logger.info('%s edited %s of %s' % (member,context.id,student_id))
        elif context.portal_type == "StudentClearance":
            matric_no = ds.get('matric_no')
            #student_id = context.getStudentId()
            context.students_catalog.modifyRecord(id = student_id,
                                                  matric_no = matric_no,
                                                 )
            logger.info('%s edited %s of %s' % (member,context.id,student_id))
        elif context.portal_type in ("StudentPersonal",):
            name = "%(firstname)s %(middlename)s %(lastname)s" % ds
            name = name.strip()
            name = name.replace('  ',' ')
            email = ds.get('email')
            phone = ds.get('phone')
            #student_id = context.getStudentId()
            #app_doc = context.application.getContent()
            #jamb_sex = 'M'
            #if ds.get('sex'):
            #    jamb_sex = 'F'
            # originally imported data must be kept; app_doc should not be changed here
            #app_doc.edit(mapping={'jamb_lastname': name,
            #                      'jamb_sex': jamb_sex
            #                      })
            context.students_catalog.modifyRecord(id = student_id,
                                                  name = name,
                                                  email = email,
                                                  phone = phone,
                                                  sex = ds.get('sex'),
                                                 )
            logger.info('%s edited %s of %s' % (member,context.id,student_id))
        elif context.portal_type == "xxxxCourse": # disabled handled by events
            dd = {}
            dd.update(ds) # ds is not a real dictionary
            try:
                context.courses_catalog.modifyRecord(**dd)
            except KeyError:
                context.courses_catalog.addRecord(**dd)
    ###################################################


    if cpsdocument_edit_and_view_button is not None:
        action = ''
    psm = 'psm_content_changed'
    args = {}
else:
    psm = 'psm_content_error'
    args = getFormUidUrlArg(REQUEST)

logger.info('%s edited %s %s of %s' % (member,context.portal_type,context.id,student_id))
args['portal_status_message'] = psm
url = context.absolute_url() + action + '?' + urlencode(args)
REQUEST.RESPONSE.redirect(url)

