##parameters=REQUEST
# $Id: book_accommodation.py 166 2005-11-12 14:45:08Z joachim $
"""
book an accomodation
"""
import DateTime
current = DateTime.DateTime()

type_name = 'Student'
ti = context.portal_types[type_name]
pm = context.portal_membership
REQUEST.set('type_name',type_name)

validate = REQUEST.has_key("cpsdocument_edit_button")


lt = context.portal_layouts
pr = context.portal_registration

res,psm,ds = lt.renderLayout(layout_id= 'accobook',
                      schema_id= 'student_accommodation',
                      context=context,
                      mapping=validate and REQUEST,
                      ob={},
                      layout_mode='create',
                      submit = "book",
                      action = 'book_accommodation',
                      )
if psm == 'invalid':
    return context.book_accommodation_form(rendered = res,
                                 psm = "Please correct your input",
                                 ds = ds,
                                 )
elif psm == '':
    return context.book_accommodation_form(rendered = res,
                                 psm = None,
                                 ds = ds,
                                 )
elif psm == 'valid':
    sf = context.getContent()
    halls = getattr(context,'accommodation').contentValues()
    beds = []
    student = context.PERSONAL.getContent()
    sf = context.getContent()
    for hall in halls:
        h = hall.getContent()
        ba = int(getattr(h,'beds_assigned',0))
        bal = getattr(h,'beds_assigned_list',[])
        nr_of_beds = int(h.nr_of_blocks) * int(h.nr_of_floors) * int(h.rooms_per_floor) * int(h.beds_per_room)
        if h.which_sex == student.sex and nr_of_beds > len(bal):
            break
    dict = {'heading': h.heading,
            'text': h.text,
            'which_sex': h.which_sex,
            'nr_of_blocks': h.nr_of_blocks,
            'nr_of_floors': h.nr_of_floors,
            'rooms_per_floor': h.rooms_per_floor,
            'beds_per_room': h.beds_per_room,
            'nr_of_free': nr_of_beds,
            'beds_assigned': ba,
             }
    ba += 1
    dict['beds_assigned'] = ba
    bal.append(('%s:%d' % (pm.getAuthenticatedMember(),ba)))
    dict['beds_assigned_list'] = bal
    h.edit(mapping = dict)
    ds.set('accommodation', "Bed # %(beds_assigned)s in %(heading)s" % dict)
    sf.edit(mapping = ds)
    #psm = "Your not admitted"
    psm = "h:%(heading)s free:%(nr_of_free)s %(beds_assigned)s" % dict

    ds.set('sc_date',current)
    sf.setScratchCardData('accommodation',ds)

    return context.booked_accommodation(v=dict)
