## Script (Python) "ti_507_resolve"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=
##title=
##
# $Id: ti_507_resolve.py 3376 2008-03-26 10:11:44Z joachim $
"""
"""
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','joachim'):
    return

import logging
import DateTime
logger = logging.getLogger('Skins.ti_507_resolve')
from Products.AdvancedQuery import Eq, Between, Le,In
aq_students = context.students_catalog.evalAdvancedQuery
aq_portal = context.portal_catalog_real.evalAdvancedQuery
students_folder = context.portal_url.getPortalObject().campus.students

request = context.REQUEST
session = request.SESSION
response = request.RESPONSE
setheader = request.RESPONSE.setHeader
logger.info('start')
count = 0
found = 0
commit_after = 1000
certificates = context.getCertificatesDict()
students = context.students_catalog()
wrong = {}
missing_courses = []
wrong_modes = {}
students_with_missing_courses = []
for student in students:
    count += 1
    if student.mode and student.course:
        certificate = certificates.get(student.course,None)
        if certificate is None:
            students_with_missing_courses += student.id,
            if student.course not in missing_courses:
                missing_courses += student.course,
                #logger.info('missing course %s' % student.course)
            continue
        current_mode = student.mode
        study_mode = certificate.get('study_mode','xxx')
        if current_mode != study_mode:
            w_count =  wrong_modes.get((current_mode,study_mode),0)
            if w_count == 0:
                logger.info('%s != %s' % (student.mode,
                                          study_mode))
            w_count += 1
            wrong_modes[(current_mode,study_mode)] = w_count
            d = {}
            d['student_id'] = student.id
            d['current_mode'] = study_mode
            d['current_mode_old'] = current_mode
            wrong[student.id] = d
    # if wrong and not (len(wrong) % commit_after):
    #     logger.info('found %d wrong of %d' % (len(wrong),count))
for k,v in wrong_modes.items():
    logger.info('wrong mode %s counted %d' % (k,v))
logger.info('missing courses %s (%d counted)' % (', '.join(missing_courses),len(students_with_missing_courses)))
logger.info('found %d wrong of %d' % (len(wrong),count))
count = 0
for student_id,d in wrong.items():
    #set_trace()
    try:
        getattr(getattr(students_folder,student_id),'study_course').getContent().edit(mapping=d)
        failed = False
    except:
        failed = True
    if failed:
        logger.info("%(student_id)s change failed")
    else:
        logger.info("%(student_id)s changed current_mode from %(current_mode_old)s to %(current_mode)s" % d)
    if count and not count % commit_after:
        context.waeup_tool.doCommit()
        logger.info("committing %d of total %d" % (commit_after,count))
    count += 1
