## Script (Python) "clearance_edit"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=REQUEST, acknowledge=None
##title=
# $Id: clearance_edit.py 2013 2007-07-12 16:12:23Z henrik $
"""
"""
wftool = context.portal_workflow
from urllib import urlencode
from Products.CPSDocument.utils import getFormUidUrlArg
import DateTime
current = DateTime.DateTime()
import logging
logger = logging.getLogger('Skins.clearance_edit')
request = REQUEST

cpsdocument_edit_button = REQUEST.has_key('cpsdocument_edit_button')
cpsdocument_edit_and_view_button = REQUEST.has_key('cpsdocument_edit_and_view_button')
clear_and_validate_button = REQUEST.has_key('clear_and_validate_button')
reject_clearance_button = REQUEST.has_key('reject_clearance_button')
result_edit_button = REQUEST.has_key('result_edit_button')

# Until ajax posts directly to its own script...
##if 'ajax_edit' in REQUEST.form:
##    return context.cpsdocument_edit_ajax(REQUEST, cluster=cluster)

# Validate the document and write it if it's valid
# (We don't call getEditableContent here, validate does it when needed.)
wftool = context.portal_workflow
info = context.getClearanceInfo()

#'Sorry, you are not allowed to access this page!'
if info == None:
  return REQUEST.RESPONSE.redirect(context.standard_error_message())
student = info['student']
#app = info['app']
#app_doc = info['app_doc']
clear = info['clear']
clear_doc = info['clear_doc']
student_id = info['id']
member_id = str(context.portal_membership.getAuthenticatedMember())
result_widgets = ('fst_sit_results',
                  'scd_sit_results',
                  'alr_results',
                  )
required_scans = ('fst_sit_scan',
#                 'jamb_slip',
                  'ref_let',
                  'acc_let'
                 )
form = request.form
psm = ""
args = {}
action = "/external_clearance_edit_form"
clearance_closed = False

if context.isStudent():
    action = "/clearance_edit_form"
    if info['clear_review_state'] == 'closed':
        clearance_closed = True

if not clearance_closed:
    is_valid, ds = clear_doc.validate(request=REQUEST,
                                schema_id = 'student_clearance',
                                layout_id = 'student_clearance',
                                proxy=clear,
                                use_session=True)
if clear_and_validate_button and info['review_state'] == "clearance_requested":
    logger.info('%s cleared %s' % (member_id,student_id ))
    #from Products.zdb import set_trace
    #set_trace()
    info['clear_doc'].edit(mapping = {'cleared_date': current,})
    wftool.doActionFor(info['student'],'clear_and_validate')
    psm = "Clearance and eligibility record is validated and student is cleared!"
elif clear_and_validate_button and info['review_state'] == "cleared_and_validated":
    psm = "This student is already cleared!"
elif reject_clearance_button:
    logger.info('%s rejected clearance for %s' % (member_id,student_id ))
    wftool.doActionFor(info['clear'],'open')
    wftool.doActionFor(info['student'],'reject_clearance')
    action = "/external_contact_student_form"
    psm = "Student's clearance request has been rejected! Please fill and submit the form below!"
    subject = "Clearance request rejected"
    args['subject'] = subject
    args['continue'] = 'external_clearance_edit_form'
elif clearance_closed:
    action = "/clearance_view"
    logger.info('%s tried to edit closed clearance object of %s' % (member_id,student_id ))
elif is_valid:
    if cpsdocument_edit_button or result_edit_button:
        psm = "Content changed!"
        logger.info('%s edited clearance object of %s' % (member_id,student_id ))

        ## No idea why the following lines were still active until July 6.
        ## The code does not make any sense. When editing the clearance object 
        ## as admin, always the PIN HOS-1-4921190317
        ## was filled in. This was the only PIN ever used by admin.
        
        #if clear_doc.clr_ac_pin == "":
        #    res = context.portal_pins(student=member_id)
        #    if res:
        #        p = res[0].pin
        #        if len(p) > 10:
        #            pin = "%s-%s-%s" % (p[:3],p[3:4],p[4:])
        #        else:
        #            pin = p
        #        clear_doc.edit(mapping={'clr_ac_pin': pin})

        ## simple method to remove the wrong PIN
        
        #if clear_doc.clr_ac_pin.startswith('HOS'):
        #    pin=''
        #    clear_doc.edit(mapping={'clr_ac_pin': pin})


    elif cpsdocument_edit_and_view_button:
        if acknowledge and info['review_state'] == "clearance_pin_entered":
            missing = False
            files = clear_doc.objectIds()
            for scan in required_scans:
                if scan not in files:
                    missing = True
                    break
            if not missing:
                if not "age_dec" in files and not "birth_certificate" in files:
                    missing = True
            if missing:
                logger.info('%s requested clearance with documents missing' % (student_id))
                psm = "You have not uploaded all necessary documents to request clearance!"
            else:
                logger.info('%s requested clearance' % (student_id))
                info['clear_doc'].edit(mapping = {'request_date': current,})
                wftool.doActionFor(info['clear'],'close')
                wftool.doActionFor(info['student'],'request_clearance',dest_container=1)
                psm = "You successfully requested clearance!"
                if context.isStudent():
                    action = "/clearance_view"
        elif acknowledge and info['review_state'] != "clearance_pin_entered":
            logger.info('%s repeatedly requested clearance' % (student_id))
            psm = "You have already requested clearance!"
        else:
            psm = "You must tick the acknowledgement check box before submission!"
else:
    psm = "Please correct your errors!"
    args = getFormUidUrlArg(REQUEST)
    logger.info('%s got error when editing the clearance object of %s' % (member_id,student_id))

args['portal_status_message'] = psm
url = clear.absolute_url() + action + '?' + urlencode(args)
return REQUEST.RESPONSE.redirect(url)

