## Script (Python) "apply_admission"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=REQUEST
##title=
##
# $Id: apply_admission.py 7979 2012-03-26 05:18:51Z henrik $
"""
process the Application Form
"""
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass

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

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

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

#manage = "manage" in request.keys()
screening_types = ('prence','pume','pume2','pce','pde','pde2','cest','sandwich',
    'dp','ct','pt','sandwich2008','pg_ft','pg_pt')
if not (traverse_subpath and traverse_subpath[0] in screening_types):
    return request.RESPONSE.redirect("%s/srp_anonymous_view" % context.portal_url())
configuration = []
headings = {}
headings['pume'] = 'Apply for Post UME Screening Test (2010/2011)! '
headings['pume2'] = 'Apply for Post UME Screening Test 2010/2011 (Uniben as 2nd choice)!'
headings['pde'] = 'Apply for Post UDE Screening Test (2010/2011)! '
headings['pde2'] = 'Apply for Post UDE Screening Test 2010/2011 (Uniben as 2nd choice)!'
headings['prence'] = 'Apply for Pre-NCE Programme (2007/2008)! '
headings['pce'] = 'Apply for PCE Screening (2009/2010)! '
headings['sandwich2008'] = 'Apply for Part Time Degree in Education (2008/2009)! '
headings['cest'] = 'Apply for Part-Time Degree Programmes (2009/2010)! '
headings['pt'] = 'Apply for Part-Time Degree Programmes (2009/2010)! '
headings['dp'] = 'Apply for Diploma Programmes (2009/2010)! '
headings['ct'] = 'Apply for Certificate Programmes (2009/2010)! '
headings['sandwich'] = 'Apply for Part Time Degree in Education (2009/2010)! '
headings['pg_pt'] = 'Apply for Postgraduate Programmes Part-Time (2011/2012)! '
headings['pg_ft'] = 'Apply for Postgraduate Programmes Full-Time (2011/2012)! '
configuration += ('heading',headings),

headings_slip = {}
headings_slip['pume'] = 'Post UME Screening (2010/2011) Acknowledgement Slip!'
headings_slip['pume2'] = 'Post UME Screening (2010/2011) Acknowledgement Slip (Uniben 2nd choice)!'
headings_slip['pde'] = 'Post UDE Screening (2010/2011) Acknowledgement Slip'
headings_slip['pde2'] = 'Post PUDE Screening (2010/2011) Acknowledgement Slip (Uniben 2nd choice)!'
headings_slip['prence'] = 'Pre-NCE Application (2007/2008) Acknowledgement Slip'
headings_slip['pce'] = 'PCE Screening (2009/2010) Acknowledgement Slip'
headings_slip['sandwich2008'] = 'Application for Part Time Degree in Education (2008/2009) Acknowledgement Slip'
headings_slip['cest'] = 'CEST Application (2009/2010) Acknowledgement Slip'
headings_slip['pt'] = 'Part-Time Degree Application (2009/2010) Acknowledgement Slip'
headings_slip['dp'] = 'Diploma Programme Application (2009/2010) Acknowledgement Slip'
headings_slip['ct'] = 'Certificate Programme Application (2009/2010) Acknowledgement Slip'
headings_slip['sandwich'] = 'Application for Part Time Degree in Education (2009/2010) Acknowledgement Slip'
headings_slip['pg_ft'] = 'Application for Postgraduate Programmes Full-Time (2011/2012) Acknowledgement Slip! '
headings_slip['pg_pt'] = 'Application for Postgraduate Programmes Part-Time (2011/2012) Acknowledgement Slip! '
configuration += ('heading_slip',headings_slip),

deaddates = {}

#config_params = context.getConfigParams()
#deaddates['pume'] = config_params['dead_pume']

deaddates['pume'] = DateTime.DateTime(pprops.date1)
deaddates['pume2'] = DateTime.DateTime(pprops.date1)
deaddates['pde'] = DateTime.DateTime(pprops.date2)
deaddates['pde2'] = DateTime.DateTime(pprops.date2)
deaddates['prence'] = DateTime.DateTime(pprops.date1)
deaddates['pce'] = DateTime.DateTime(pprops.date5)
deaddates['sandwich2008'] = DateTime.DateTime(pprops.date1)  #is expired like pume
deaddates['cest'] = DateTime.DateTime(pprops.date3)
deaddates['sandwich'] = DateTime.DateTime(pprops.date4)
deaddates['pt'] = DateTime.DateTime(pprops.date5)
deaddates['dp'] = DateTime.DateTime(pprops.date5)
deaddates['ct'] = DateTime.DateTime(pprops.date5)
deaddates['pg_ft'] = DateTime.DateTime(pprops.date5)
deaddates['pg_pt'] = DateTime.DateTime(pprops.date5)
configuration += ('deaddate',deaddates),

deadline = {}
for sct in screening_types:
    deadline[sct] = deaddates[sct].strftime('%A, %d. %B %Y at %I:%M %p')
configuration += ('deadline',deadline),

confirm = {}
confirm['pume'] = "I confirm that the Passport Photograph uploaded on this form is a true picture of me."
confirm['pume2'] = "I confirm that the Passport Photograph uploaded on this form is a true picture of me."
confirm['pde'] = "I confirm that the Passport Photograph uploaded on this form is a true picture of me."
confirm['pde2'] = "I confirm that the Passport Photograph uploaded on this form is a true picture of me."
confirm['prence'] = "I confirm that the Passport Photograph uploaded on this form is a true picture of me."
confirm['pce'] = "I confirm that the Passport Photograph uploaded on this form is a true picture of me."
confirm['cest'] = confirm['sandwich'] = confirm['pt'] = confirm['dp'] = confirm['ct'] = confirm['sandwich2008'] = confirm['pg_ft']= confirm['pg_pt'] = """I hereby acknowledge
by ticking this check box that if it is discovered
at any time, that I do not possess any of the qualifications, which I have obtained, I will be
expelled from the University and shall not be readmitted for the same or any other programme,
even if I have upgraded my previous qualification or posses additional qualifications."""
configuration += ('confirm',confirm),

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

without_reg_no = False


lt = context.portal_layouts
object = {}
pin = request.form.get('pin','')
# reg_no = request.get('widget__reg_no','').upper()
# if not reg_no:
#     reg_no = request.form.get('reg_no','').upper()
info = {}
screening_type = 'pume'
if traverse_subpath and traverse_subpath[0] in screening_types:
    screening_type = traverse_subpath[0]
without_reg_no = screening_type in ('prence','cest','sandwich','sandwich2008','dp','pt','ct')
info['expired'] = current.greaterThan(deaddates[screening_type])
info['expiration_date'] = deaddates[screening_type]
info['status'] = object.get('status','')
info['screening_type'] = screening_type
layout = "application_%s" % screening_type
for co_name,co_dict in configuration:
    info[co_name] = co_dict[screening_type]
# the reg_no is a hidden field in the form
reg_no = request.form.get('reg_no','').upper()

if not reg_no:
    # validate form if no reg_no specified
    res,psm,ds = lt.renderLayout(layout_id= layout,
                                schema_id= 'import_application',
                                layout_mode = mode,
                                context=context,
                                mapping=validate and REQUEST,
                                ob={},
                                commit = False,
                                )
    if psm == 'invalid':
        return context.apply_admission_form(rendered = res,
                                            psm = "Please correct your input!",
                                            mode = mode,
                                            ds = ds,
                                            info = info,
                                        )
    elif psm == '':
        return context.apply_admission_form(rendered = res,
                                            psm = psm,
                                            ds = ds,
                                            mode = mode,
                                            info = info,
                                           )
    if without_reg_no:
        ## see fceokene #147 
        if screening_type == 'sandwich2008':
            reg_no = ds.get('pin_n','').upper()
        else:
            reg_no = ds.get('pin_p') + ds.get('pin_b') + ds.get('pin_n')
    else:
        reg_no = ds.get('reg_no')
info['reg_no'] = reg_no

brains = context.applicants_catalog(reg_no = reg_no.upper())
if len(brains) == 1:
    for field in context.applicants_catalog.schema():
        object[field] = getattr(brains[0],field,None)
    screening_type = info['screening_type'] = object['screening_type']
    for co_name,co_dict in configuration:
        info[co_name] = co_dict[screening_type]
    if not object['passport']:
            object['passport'] = ''
    if object['status'] and ('submitted' in object['status'] or 'admitted' in object['status'] or 'created' in object['status']):
        submitted = True
    # cannot happen anymore but anyway
    #if not (create or slip) and (pin != object['pin'] and not context.isSectionOfficer()):
    #    logger.info('%s/%s entered wrong pin %s' % (member,reg_no,pin))
    #    return request.RESPONSE.redirect("%s/srp_anonymous_view" % context.portal_url())

    #rerender with current object = application-record

    if slip:
        mode = "view_slip"
        logger.info('%s/%s views application slip' % (member,reg_no))

    res,psm,ds = lt.renderLayout(layout_id= layout,
                                schema_id= 'import_application',
                                layout_mode = mode,
                                context=context,
                                mapping=validate and REQUEST,
                                ob=object,
                                commit = False,
                                )
    if slip:
        return context.apply_admission_slip(rendered = res,
                                            psm = "",
                                            mode = mode,
                                            ds = ds,
                                            info = info,
                                           )

    if psm == 'invalid':
        return context.apply_admission_form(rendered = res,
                                            psm = "Please correct your input!",
                                            mode = mode,
                                            ds = ds,
                                            info = info,
                                        )
    # For the next application session it should be reverted to
    # (see comment 09/06/07 16:40:52 in ticket #328):

    #if not create and (pin != object['pin'] and not context.isSectionOfficer()):
        #logger.info('%s/%s entered wrong pin %s' % (member,reg_no,pin))
        #return request.RESPONSE.redirect("%s/srp_anonymous_view" % context.portal_url())
info['status'] = object.get('status','')

data = {}
dm = ds.getDataModel()
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_admission:
    if submitted:
        mode = "view"
        psm = "The form has already been submitted and you are not allowed to resubmit the data!"
        logger.info('%s/%s tried to resubmit application record' % (member,reg_no))
        # res,psm_dummy,ds_dummy = lt.renderLayout(layout_id= layout,
        #                         schema_id= 'import_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/%s tried to submit without ticking confirmation check box' % (member,reg_no))
    else:
        mode = "view"
        psm = "You successfully applied for admission!"
        if object['status'] == 'edited':
            data['status'] = "submitted"
            data['application_date'] = current
            logger.info('%s/%s modified and submitted application record' % (member,reg_no))
        elif object['status'] == 'reset':
            data['status'] = 'resubmitted on %s' % DateTime.DateTime().strftime('%A, %B %d, %Y')
            logger.info('%s/%s modified and resubmitted application record' % (member,reg_no))
        object['status'] = data['status']
        context.applicants_catalog.modifyRecord(**data)
        # rerendering neccessary since object changed
        res,psm_dummy,ds = lt.renderLayout(layout_id= layout,
                                schema_id= 'import_application',
                                layout_mode = mode,
                                context=context,
                                mapping=validate and REQUEST,
                                ob=object,
                                commit = False,
                                )
elif create:
    if submitted:
        mode = "view"
        logger.info('%s/%s is viewing application record' % (member,reg_no))
    else:
        mode = "edit"
        logger.info('%s/%s started editing application record' % (member,reg_no))
    psm = ""
    if without_reg_no:
        object['reg_no'] = reg_no
    object['pin'] = str(ds.get('pin'))
    # rerendering neccessary since object changed
    res,psm,ds_dummy = lt.renderLayout(layout_id= layout,
                                schema_id= 'import_application',
                                layout_mode = mode,
                                context=context,
                                mapping={},
                                ob=object,
                                commit = False,
                                )
elif edit:
    if submitted:
        mode = "view"
        psm = "The form has already been submitted and you are not allowed to modify the data!"
        logger.info('%s/%s tried to edit submitted application record' % (member,reg_no))
        # res,psm_dummy,ds_dummy = lt.renderLayout(layout_id= layout,
        #                         schema_id= 'import_application',
        #                         layout_mode = mode,
        #                         context=context,
        #                         mapping={},
        #                         ob=object,
        #                         commit = False,
        #                         )
    else:
        mode = "edit"
        psm = "Content changed!"
        data['status'] = "edited"
        #set_trace()
        context.applicants_catalog.modifyRecord(**data)
        logger.info('%s/%s modified application record' % (member,reg_no))

try:
    passport_uploaded = bool(data['passport'])
except:
    passport_uploaded = False

return context.apply_admission_form(rendered = res,
                                    psm = psm,
                                    mode = mode,
                                    show_submit = passport_uploaded,
                                    ds = ds,
                                    info = info,
                              )
