## 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 902 2006-11-20 07:39:43Z joachim $
"""
"""
wftool = context.portal_workflow
from urllib import urlencode
from Products.CPSDocument.utils import getFormUidUrlArg
import DateTime
current = DateTime.DateTime()

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')

# 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.getStudentInfo()

student = info['student']
app = info['app']
app_doc = info['app_doc']
clear = info['clear']
clear_doc = info['clear_doc']

is_valid, ds = clear_doc.validate(request=REQUEST,
                                schema_id = 'student_clearance',
                                layout_id = 'student_clearance',
                                proxy=clear,
                                use_session=True)

psm = ""
args = {}
action = "/external_clearance_edit_form"
if is_valid:
    if cpsdocument_edit_button:
        psm = "Content changed!"
    elif cpsdocument_edit_and_view_button:
        if acknowledge:
            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"
        else:
            psm = "You must tick the acknowledgement check box before submission!"
            if context.isStudent():
               action = "/clearance_edit_form"
    elif clear_and_validate_button:
        wftool.doActionFor(info['student'],'clear_and_validate')
        psm = "Clearance and eligibility record is validated and and student is cleared!"
    elif reject_clearance_button:
        wftool.doActionFor(info['clear'],'open')
        wftool.doActionFor(info['student'],'reject_clearance')
        action = "/contact_student_form"
        psm = "Student's clearance request has been rejected! Please fill and submit the form below!"
else:
    psm = "Please correct your errors!"
    args = getFormUidUrlArg(REQUEST)

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