## Script (Python) "search_students"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=REQUEST
##title=
##
# $Id: search_students.py 911 2006-11-20 15:11:29Z henrik $
"""
list Students for ClearanceOfficers
"""
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass
import logging
logger = logging.getLogger('Skins.search_students')
#from DateTime import DateTime
#
#with_timer = True
#with_timer = False
#
request = REQUEST
form = request.form
fget = form.get
mtool = context.portal_membership
member = mtool.getAuthenticatedMember()
is_anon = mtool.isAnonymousUser()
lt = context.portal_layouts
path_info = request.get('PATH_INFO').split('/')

allowed = True
if is_anon or context.isStudent():
    allowed = False
from Products.AdvancedQuery import Eq, Between, Le,In
try:
    aq_portal = context.portal_catalog.evalAdvancedQuery
except:
    aq_portal = context.portal_catalog_real.evalAdvancedQuery
students_catalog = context.students_catalog
aq_students = students_catalog.evalAdvancedQuery

#def cmp_id(a,b):
#    if a.getId() > b.getId():
#        return 1
#    return -1

user_info = {}
validate = request.has_key("cpsdocument_edit_button")

default_state = "all"
user_info['member'] = str(member)
user_info['departments'] = []
user_info['faculties'] = []
user_info['certificates'] = []
co_view = False
ca_view = False
session_data = request.SESSION
faculties =  session_data.get('faculties',None)
departments = session_data.get('departments',None)
certificates = session_data.get('certificates',None)
certificate_levels = session_data.get('certificate_levels',None)
# determine local roles
if "ClearanceOfficers" in member.getGroups():
    default_state = "clearance_requested"
    co_view = True
    if faculties is None or departments is None or certificates is None:
        logger.info('ClearanceOfficer %s initiated student_search' % member)
        query = In('portal_type',('Faculty','Department','Certificate')) &\
                 In('localUsersWithRoles', ("user:%s" % member,))
        res = aq_portal(query)
        faculties = [f.getId for f in res if f.portal_type == 'Faculty']
        departments = [f.getId for f in res if f.portal_type == 'Department']
        certificates = [f.getId for f in res if f.portal_type == 'Certificate']
    user_info['faculties'] = session_data['faculties'] = faculties
    user_info['departments'] = session_data['departments'] =  departments
    user_info['certificates'] = session_data['certificates'] =  certificates
if "CourseAdvisers" in member.getGroups():
    default_state = "courses_registered"
    ca_view = True
    if certificate_levels is None:
        logger.info('CourseAdviser %s initiated student_search' % member)
        query = In('portal_type',('StudyLevel',)) &\
                 In('localUsersWithRoles', ("user:%s" % member,))
        res = aq_portal(query)
        certificate_levels = ['/'.join(f.getPath().split('/')[-2:]) for f in res]
        cert_ids = []
        level_ids = []
        for cl in certificate_levels:
            c,l = cl.split('/')
            level_ids += l,
            if c not in cert_ids:
                cert_ids += c,
        cert_brains = aq_portal(In("id",cert_ids))
        end_levels = {}
        for cert_brain in cert_brains:
            end_levels[cert_brain.getId] = cert_brain.getObject().getContent().end_level
        for cl in certificate_levels[:]:
            c,l = cl.split('/')
            for prob in (10,20):
                certificate_levels += "%s/%s" % (c,int(l) + prob),
            if l == end_levels[c]:
                certificate_levels += "%s/%s" % (c,int(l) + 100),
                certificate_levels += "%s/%s" % (c,int(l) + 110),
    user_info['certificate_levels'] = session_data['certificate_levels'] = certificate_levels

default = {'search_mode': 'student_id',
        'review_state': default_state,
        'search_string': ''
        }
rend,psm,ds = lt.renderLayout(layout_id= 'student_search',
                      schema_id= 'student_search',
                      context=context,
                      mapping=validate and REQUEST,
                      ob=default,
                      layout_mode='edit',
                      formaction="search_students",
                      commit = False,
                      )
if psm == '':
    return context.search_students_form(rendered = rend,
                             psm = psm,
                             #psm = "%s, %s" % (psm,ds),
                             info = user_info,
                             students = [],
                             allowed = allowed,
                             )
                             
# return to search form  if form was not properly filled
                             
what = ds.get('search_mode')
state = ds.get('review_state')
st = term = ds.get('search_string')
err = False
if not term and state == "all":
    psm = "You must specify a search string when searching for students in all states!"
    err = True
elif '*' in term:
    psm = "Wildcards are not supported!"
    err = True
if err:
    return context.search_students_form(rendered = rend,
                             psm = psm,
                             #psm = "%s, %s" % (psm,ds),
                             info = user_info,
                             students = [],
                             allowed = allowed,
                             )

# build query string part 1

query = None
if len(term) > 0:
    if what == "student_id":
        students_folder = context.portal_url.getPortalObject().campus.students
        if hasattr(students_folder,term.strip()):
            logger.info('%s searches for student with id %s' % (member,term))
            request.RESPONSE.redirect("%s/%s" % (students_folder.absolute_url(),term))
        return context.search_students_form(rendered = rend,
                             psm = "No student found!",
                             students = [],
                             allowed = allowed,
                             info = user_info,
                             )
    elif what == "department":
        query = Eq('department', term.strip())
        logger.info('%s searches for student in department %s' % (member,term))
    elif what == "matric_no":
        query = Eq('matric_no', term.strip())
        logger.info('%s searches for student with matric_no %s' % (member,term))
    elif what == "jamb_reg_no":
        st_l = "%s" % term.strip().lower()
        st_u = "%s" % term.strip().upper()
        query = In('jamb_reg_no',(st_l,st_u))
        logger.info('%s searches for student with jamb_reg_no %s' % (member,term))
    elif what == "name":
        if len(term) < 4:
            return context.search_students_form(rendered = rend,
                                                psm = "Search string is too short!",
                                                students = [],
                                                info = user_info,
                                                allowed = allowed,
                                               )
        query = Eq('name',"%s*" % term.strip())
        logger.info('%s searches for student with name %s' % (member,term))


# build query string part 2

if state != 'all':
    if query is not None:
        query = Eq('review_state',state) & query
    else:
        query = Eq('review_state',state)
    logger.info('%s searches for students in review_state %s' % (member,state))

# build query string part 3
if co_view and state.startswith('clear'):
    if query is not None:
        query = query & (In('faculty',faculties) | In('department',departments) | In('course',certificates))
    else:
        query = In('faculty',faculties) | In('department',departments) | In('course',certificates)
elif ca_view and state.startswith('courses'):
    courses = [cl.split('/')[0] for cl in certificate_levels]
    levels = [cl.split('/')[1] for cl in certificate_levels]
    if query is not None:
        query = query & In('course',courses) & In('level',levels)

# search students_catalog

#return query

student_records = aq_students(query,('matric_no','jamb_reg_no'))
students = []
if student_records:
    for student_record in student_records:
        
        #ensure that course/level combinations are correct (see ticket #574)
        if ca_view:
           course = getattr(student_record, 'course')
           level = getattr(student_record, 'level')
           if course+'/'+level not in certificate_levels:
               continue
               
        info = {}
        for field in students_catalog.schema() + students_catalog.indexes():
            info[field] = getattr(student_record, field)
        else:
            students.append(info)
    return context.search_students_form(rendered = rend,
                             psm = "",
                             info = user_info,
                             students = students,
                             allowed = allowed,
                             co_view = state.startswith('clear'),
                             ca_view = state.startswith('courses')
                             )
return context.search_students_form(rendered = rend,
                             psm = "No student found!",
                             info = user_info,
                             students = students,
                             allowed = allowed,
                             )


