## Script (Python) "change_bed"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
# $Id: change_bed.py 3425 2008-04-07 07:24:40Z henrik $
"""
relocate to a new bed if allocated bed is wrong
"""
import logging
from Products.AdvancedQuery import Eq, Between, Le,In

logger = logging.getLogger('Skins.change_bed')
request = context.REQUEST
redirect = request.RESPONSE.redirect
mtool = context.portal_membership
wf = context.portal_workflow
member = mtool.getAuthenticatedMember()
member_id = str(member)
path_info = request.get('PATH_INFO').split('/')

if mtool.isAnonymousUser():
    return None
students = context.portal_url.getPortalObject().campus.students
beds = context.portal_accommodation
studs = context.students_catalog
student_id = context.getStudentId()

if student_id is not None:
    logger.info('%s requests bed change for %s' % (member_id,student_id))
    info = context.getAccommodationInfo(student_id)
    if info['acco'] is None:
        logger.info('No accommodation object for %s' % (student_id))
        return redirect("%s/%s/no_booking_allowed" % (students.absolute_url(),student_id))
    res = beds(student=student_id)
    status = info['student_status']
    while True:
        if len(res) == 0:
            psm = 'No bed allocated for %s' % (student_id)
            logger.info(psm)
            pass
            #break
        elif res[0].bed_type.endswith("reserved"):
             logger.info("found reserved bed %s which won't be released" % res[0].bed)
             pass
        else:
            allocated_bed = res[0]
            if allocated_bed.bed_type == status:
                logger.info('Status %s of %s has not changed.' % (status,student_id))
                psm='Student status has not changed!'
                break
                #return redirect("%s/%s/%s/waeup_document_view?portal_status_message=%s" % (students.absolute_url(),student_id,info['acco_id'],psm))
            logger.info('Bed status %s of %s has changed to %s.' % (allocated_bed.bed_type,student_id,status))
            query = Eq('bed_type',status) & Eq('student',context.portal_accommodation.not_occupied)
            records = context.portal_accommodation.evalAdvancedQuery(query)
            if len(records) < 1:
                psm='Bed change for %s failed, no free bed in category %s.' % (student_id,status)
                logger.info(psm)
                break
            beds.modifyRecord(bed=allocated_bed.bed,student=beds.not_occupied)
            logger.info('Bed %s released' % (allocated_bed.bed))
        code,bed = beds.searchAndReserveBed(student_id,status)
        if code > -2:
            d = {}
            d['bed'] = bed
            d['student_status'] = status
            acco_info = context.waeup_tool.getHallInfo(bed)
            d['acco_maint_code'] = acco_info.get('maintenance_code')
            d['acco_maint_fee'] = acco_info.get('maintenance_fee')
            acco_doc = info['acco_doc']
            acco_doc.edit(mapping=d)
        if code > 0:
            psm = 'Bed changed!'
            logger.info('Bed %s allocated to %s' % (bed,student_id))
        elif code == -1:
            psm = 'A reserved bed has been allocated.'
        elif code == -2:
            psm = 'No bed %s for %s available!' % (status,student_id)
        else:
            psm = 'Bed change failed!'
        break
    return redirect("%s/%s/%s/waeup_document_view?portal_status_message=%s" % (students.absolute_url(),student_id,info['acco_id'],psm))

info = {}
records = [r for r in beds() if  r.student and  r.student != beds.not_occupied]
list = []
to_modify = []
logger.info('started without student context')
for r in records:
    info = context.getAccommodationInfo(r.student)
    sbt = info.get('student_status',None)
    if sbt is None:
        continue
    elif r.bed_type == sbt or r.bed_type.endswith('reserved'):
        #list.append("Student %s bed_type %s ok" % (r.student,r.bed_type))
        continue
    message = "Student %s bed_type %s != %s" % (r.student,
                                                  r.bed_type,
                                                  info['student_status'])
    list.append(message)
    #to_modify.append((r.bed,r.student,info['student_status'],info['acco_doc']))
    logger.info(message)
logger.info('finished')

return "\r".join(list)

for former_bed, student, status,acco_doc in to_modify:
    beds.modifyRecord(bed=former_bed,student='')
    code,bed = beds.searchAndReserveBed(student,status)
    if code > 0:
        #from Products.zdb import set_trace; set_trace()
        d = {}
        d['bed'] = bed
        d['student_status'] = status
        acco_info = context.waeup_tool.getHallInfo(bed)
        d['acco_maint_code'] = acco_info.get('maintenance_code')
        d['acco_maint_fee'] = acco_info.get('maintenance_fee')
        acco_doc.edit(mapping=d)
        list.append("New bed %s allocated to %s, code = %s" % (bed,
                                                              student,
                                                              code))
return "\r".join(list)
