## Script (Python) "apply_pume"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=REQUEST
##title=
##
# $Id: apply_pume.py 2119 2007-08-18 17:23:25Z henrik $
"""
process the Pume Application Form
"""
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass

import DateTime
import logging
logger = logging.getLogger('Skins.apply_pume')

current = DateTime.DateTime()
pr = context.portal_registration
request = REQUEST

#type_name = 'StudentApplication'
#ti = context.portal_types[type_name]
#REQUEST.set('type_name',type_name)
create = "create" in request.keys()
apply_pume = "apply" in request.keys()
edit = "edit" in request.keys()
slip = "slip" in request.keys()
submitted = False
mode = request.get('mode','')
if not mode:
    if apply_pume or edit:
        mode = "edit"
    else:
        mode = "create"
validate = create or edit or apply_pume

lt = context.portal_layouts
reg_no = request.get('widget__reg_no','').upper()
if not reg_no:
    reg_no = request.form.get('reg_no','').upper()
pin = request.form.get('pin','')
object = {}
if reg_no:
    brains = context.applicants_catalog(reg_no = reg_no)
    if len(brains) == 1:
        for field in context.applicants_catalog.schema():
            object[field] = getattr(brains[0],field,None)
        if not object['passport']:
            object['passport'] = ''
        if object['status'] == "submitted":
            submitted = True
        if not create and pin != object['pin']:
            logger.info('%s entered wrong pin %s' % (reg_no,pin))
            return request.RESPONSE.redirect("%s/srp_anonymous_view" % context.portal_url())
if slip:
    mode = "view_slip"
    logger.info('%s views application slip' % (reg_no))
    
res,psm,ds = lt.renderLayout(layout_id= 'application',
                             schema_id= 'application',
                             layout_mode = mode,
                             context=context,
                             mapping=validate and REQUEST,
                             ob=object,
                             commit = False,
                            )

if slip:
    return context.apply_pume_slip(rendered = res,
                                   psm = "",
                                   #psm = "%s, %s" % (psm,ds),
                                   mode = mode,
                                   ds = ds,
                                  )

if psm == 'invalid':
    return context.apply_pume_form(rendered = res,
                                   psm = "Please correct your input!",
                                   #psm = "%s, %s" % (psm,ds),
                                   mode = mode,
                                   ds = ds,
                                  )
elif psm == '':
    return context.apply_pume_form(rendered = res,
                                   psm = None,
                                   ds = ds,
                                   mode = mode,
                                  )
elif psm == 'valid':
    pass
data = {}
dm = ds.getDataModel()
#set_trace()
for field in context.applicants_catalog.schema():
    if dm.has_key("%s" % field):
        data[field] = dm.get(field)
data['reg_no'] = reg_no
if apply_pume:
    if submitted:
        mode = "view"
        psm = "The form has already been submitted and you are not allowed to resubmit the data!"
        logger.info('%s tried to resubmit application record' % (reg_no))
        res,psm_dummy,ds_dummy = lt.renderLayout(layout_id= 'application',
                                schema_id= 'application',
                                layout_mode = mode,
                                context=context,
                                mapping={},
                                ob=object,
                                commit = False,
                                )
    elif not request.has_key('confirm'):
        mode = "edit"
        psm = "Please confirm Passport Photograph!"
        logger.info('%s tried to submit without ticking confirmation check box' % (reg_no))
    else:
        mode = "view"
        psm = "You successfully applied for PUME!"
        data['application_date'] = current
        data['status'] = "submitted"
        context.applicants_catalog.modifyRecord(**data)
        logger.info('%s modified and submitted application record' % (reg_no))
        res,psm_dummy,ds = lt.renderLayout(layout_id= 'application',
                                schema_id= 'application',
                                layout_mode = mode,
                                context=context,
                                mapping=validate and REQUEST,
                                ob=object,
                                commit = False,
                                )
elif create:
    if submitted:
        mode = "view"
        logger.info('%s views application record' % (reg_no))
    else:
        mode = "edit"
        logger.info('%s edits application process' % (reg_no))
    psm = ""
    #set_trace()
    object['pin'] = str(ds.get('pin'))
    res,psm,ds_dummy = lt.renderLayout(layout_id= 'application',
                                schema_id= 'application',
                                layout_mode = mode,
                                context=context,
                                mapping={},
                                ob=object,
                                commit = False,
                                )
elif edit:
    #set_trace()
    if submitted:
        mode = "view"
        psm = "The form has already been submitted and you are not allowed to modify the data!"
        logger.info('%s tried to edit submitted application record' % (reg_no))
        res,psm_dummy,ds_dummy = lt.renderLayout(layout_id= 'application',
                                schema_id= 'application',
                                layout_mode = mode,
                                context=context,
                                mapping={},
                                ob=object,
                                commit = False,
                                )
    else:
        mode = "edit"
        psm = "Content changed"
        data['status'] = "edited"
        context.applicants_catalog.modifyRecord(**data)
        logger.info('%s modified application record' % (reg_no))



return context.apply_pume_form(rendered = res,
                            psm = psm,
                            #psm = "%s, %s" % (psm,ds),
                            mode = mode,
                            ds = ds,
                            )


