## Script (Python) "admitStudents"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=entry_session=''
##title=
##
# $Id: admitStudents.py 5567 2010-10-14 06:10:25Z henrik $
"""
"""
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass

mtool = context.portal_membership
member = mtool.getAuthenticatedMember()
if str(member) not in ('admin',):
    return

pin_password = False

import logging
import DateTime
logger = logging.getLogger('Skins.admitStudents')
from Products.AdvancedQuery import Eq, Between, Le,In
aq_applicants = context.applicants_catalog.evalAdvancedQuery
request = context.REQUEST
session = request.SESSION
response = request.RESPONSE
setheader = request.RESPONSE.setHeader
def rwrite(s):
    response.setHeader('Content-type','text/html; charset=ISO-8859-15')
    response.write("%s<br>\n\r" % s)

if not entry_session:
    brains = aq_applicants(In('status',('admitted'),))
else:
    brains = aq_applicants(In('status',('admitted'),) & Eq('entry_session',entry_session))

total = len(brains)
logger.info("found %d students" % (total))
count = 0
admitted = 0
cocount = 0
old_commit_count = 0
commit_after = 40
d = {'status': 'created'}
reg_nos = [brain.reg_no for brain in brains]
with_timing = False
for reg_no in reg_nos:
    count += 1
    must_commit = (admitted != old_commit_count) and (not admitted % commit_after)
    if must_commit:
        old_commit_count = admitted
        context.waeup_tool.doCommit()
        logger.info("Committing %s transactions, total %s" % (commit_after,count))
        cocount += 1
        if with_timing and cocount > 2:
            break
    brain = aq_applicants(Eq('reg_no',reg_no))[0]
    #logger.info("start creating  objects of student %s" % (brain.reg_no))
    sid = d['student_id'] = context.waeup_tool.admitOneStudent(brain,
                                                               entry_session,
                                                               pin_password,
                                                               with_timing = with_timing)

    if sid is not None:
        d['reg_no'] = reg_no
        context.applicants_catalog.modifyRecord(**d)
        logger.info("created objects of student %s with id %s" % (reg_no,sid))
        if with_timing:
            data = context.waeup_tool.get_timing_data()
            for k,d in data.items():
                s = "timing line %s" % k
                s += " %(i_time)6.2f/%(a_time)6.2f" % d
                logger.info(s)
        admitted += 1
    else:
        logger.info("could not create objects of student %s with pin %s" % (reg_no,brain.pin))

msg = "finished admitting %d students" % (admitted)
logger.info(msg)
#rwrite(msg)
return
