## Script (Python) "book_accommodation.py"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=REQUEST
# $Id: book_accommodation.py 5792 2011-03-03 13:54:24Z henrik $
"""
process the the accommodation reservation
"""
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass
import DateTime
current = DateTime.DateTime()
pr = context.portal_registration
wftool = context.portal_workflow
lt = context.portal_layouts
info = context.getAccommodationStatus()

import logging
logger = logging.getLogger('Skins.book_accommodation')

if info is None:
    member_id = str(context.portal_membership.getAuthenticatedMember())
    logger.info('%s tried to reserve accommodation' % (member_id))
    return context.REQUEST.RESPONSE.redirect("%s/srp_invalid_access" % context.portal_url())

if info['booking_disabled']:
    return context.REQUEST.RESPONSE.redirect("%s/booking_disabled" % info['student'].absolute_url())
if not info['booking_allowed']:
    return context.REQUEST.RESPONSE.redirect("%s/no_booking_allowed" % info['student'].absolute_url())
student = info['student']
student_id = info['student_id']
acco_id = info['acco_id']
session = info['session'][0]
mode = 'create'
validate = REQUEST.has_key("cpsdocument_create_button")
button = 'Book'

res,psm,ds = lt.renderLayout(layout_id= 'student_accommodation_fe',
                      schema_id= 'student_accommodation',
                      context=context,
                      mapping=validate and REQUEST,
                      ob=info,
                      layout_mode=mode,
                      formaction = "book_accommodation",
                      button = button)



if psm == 'invalid':
    member_id = str(context.portal_membership.getAuthenticatedMember())
    #logger.info('%s, %s' % (member_id,info['error'] ))
    logger.info('%s entered invalid data' % (member_id))
    psm = "Please correct your input."
    return context.book_accommodation_form(rendered = res,
                                 psm = psm,
                                 mode = mode,
                                 ds = ds,
                                 )
elif psm == '':
    return context.book_accommodation_form(rendered = res,
                                 psm = None,
                                 mode = mode,
                                 ds = ds,
                                 )
elif psm == 'valid':
    code,bed = context.portal_accommodation.searchAndReserveBed(student_id,
                                                                "%s" % (info['student_status']),
                                                                random_order=True)
    while True:
        if code == 1:
            break
        if code == -1:
            break
        elif code == -2:
            return context.book_accommodation_form(rendered = res,
                                    psm = "No bed available. Your category is already fully booked.",
                                    mode = mode,
                                    ds = ds,
                                    )
        else: # unknown error
            return context.book_accommodation_form(rendered = res,
                                    psm = "Unexpected Error!",
                                    mode = mode,
                                    ds = ds,
                                    )


hall_info = context.waeup_tool.getHallInfo(bed)
data={}
data['acco_res_sc_pin'] = str(ds.get('acco_res_sc_pin',''))
data['acco_maint_code'] = hall_info.get('maintenance_code')
data['acco_maint_fee'] = hall_info.get('maintenance_fee')
data['acco_res_date'] = current
data['bed'] = bed
data['session'] = session
data['student_status'] = info['student_status']
data['catkey'] =student_id + '|' + session
data['student_id'] = student_id
data['reservation_status'] = 'bed_reserved'

#set_trace()
context.accommodation_catalog.addRecord(**data)

return context.REQUEST.RESPONSE.redirect("%s/accommodations" % student.absolute_url())

