## Script (Python) "relocate"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=session=None
##title=
##
# $Id: relocate.py 5616 2010-12-27 10:18:18Z henrik $
"""
relocate to a new bed if allocated bed is wrong (former change_bed)
"""
import logging
from Products.AdvancedQuery import Eq, Between, Le,In

logger = logging.getLogger('Skins.relocate')
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('/')
students = context.portal_url.getPortalObject().campus.students
portal_acco_cat = context.portal_accommodation
studs = context.students_catalog
student_id = context.getStudentId()

if not context.isSectionOfficer():
    logger.info('%s tried to access %s' % (member_id,student_id))
    return None

if student_id is not None:
    logger.info('%s requests bed change for %s' % (member_id,student_id))
    info = context.getAccommodationStatus(student_id)
    res = portal_acco_cat(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
            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
            portal_acco_cat.modifyRecord(bed=allocated_bed.bed,student=portal_acco_cat.not_occupied)
            logger.info('Bed %s released' % (allocated_bed.bed))
        code,bed = portal_acco_cat.searchAndReserveBed(student_id,status,random_order=True)
        if code > -2:
            acco_info = context.waeup_tool.getHallInfo(bed)
            d = {}
            d['bed'] = bed
            d['student_status'] = status
            d['catkey'] = student_id + '|' + session
            d['acco_maint_code'] = acco_info.get('maintenance_code')
            d['acco_maint_fee'] = acco_info.get('maintenance_fee')
            context.accommodation_catalog.modifyRecord(**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/accommodations" % (students.absolute_url(),student_id))


