## Script (Python) "session_save_form"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=Introspect context schema and saves on session REQUESTs values
##

#
# This file is for Plone 2.1.x compatibility - custom 
# patch for savePostbackData was submitted to Archetypes
# Trac tracker on 23.4.2006. This file can be removed in the 
# future versions of Plone.
#
# - Mikko Ohtamaa <mikko@redinnovation.com>
#

from Products.Archetypes.utils import shasattr
from zLOG import LOG, INFO

REQUEST = context.REQUEST

# hey, don't forget to increment object number for sessions
form_data = {'HTTP_REFERER':REQUEST.get('last_referer', None)}
to_store = [f for f in context.Schema().values() if f.type != 'computed']

for field in to_store:

    fieldname = field.getName()
    LOG('DataGridField', INFO, "session_save for %s hasattr %d " % (fieldname, shasattr(field.widget, "savePostbackData")))
    # Let's check savePostbackData for backward compatibility
    if shasattr(field.widget, "savePostbackData"):        
        # Widget implements its own postback data handler
        field.widget.savePostbackData(REQUEST, context, field, form_data)    
    elif field.widget.getName() == 'KeywordWidget':
        fieldname = '%s_keywords' % field.getName()
        data = []
        if REQUEST.has_key(fieldname):
            data += REQUEST.get(fieldname)
        fieldname = '%s_existing_keywords' % field.getName()
        if REQUEST.has_key(fieldname):
            data += REQUEST.get(fieldname)
        form_data[field.getName()] = data
    else:
        if REQUEST.has_key(fieldname):
            form_data[fieldname] = REQUEST.get(fieldname)
      
# XXX Implicitly creating a session for user.
REQUEST.SESSION.set(context.getId(), form_data)
