##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 $
"""
"""
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass

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()
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)
#        return REQUEST.RESPONSE.redirect(url)
old_values = dict([(k,v) for k,v in doc.getDataModel().items()])

is_valid, ds = doc.validate(request=REQUEST, proxy=context, cluster=cluster,
                            use_session=True)
student_id = context.getStudentId()
action = "/" + came_from
if is_valid:
    # comments = REQUEST.get('comments')
    # context.cpsdocument_notify_modification(comments=comments)
    if cpsdocument_edit_and_view_button is not None:
        action = ''
    new_values = dict([(k,v) for k,v in doc.getDataModel().items()])
    changed = [ k for k in old_values.keys() if new_values[k] != old_values[k]]
    if student_id:
        logger.info('%s edited %s object (fields %s) of %s' % (member, 
                                                
                                                context.id,
                                                ', '.join(changed),
                                                student_id))
    else:
        logger.info('%s edited %s %s (fields %s)' % (member, 
                                                context.portal_type,
                                                context.id,
                                                ', '.join(changed),
                                                ))    
        
    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)

