## Script (Python) "getStudyLevelInfo"
##bind container=container
##bind context=context
##bind namespace=
##bind script=script
##bind subpath=traverse_subpath
##parameters=student=None
##title=
##
# $Id: getStudyLevelInfo.py 2286 2007-09-28 06:11:20Z henrik $
"""
return Info about the Studylevel
"""

wf = context.portal_workflow
mtool = context.portal_membership
if mtool.isAnonymousUser():
    return None

try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass


from Products.AdvancedQuery import Eq, Between, Le,In
try:
    aq_portal = context.portal_catalog.evalAdvancedQuery
except:
    aq_portal = context.portal_catalog_real.evalAdvancedQuery
request = context.REQUEST
#session = request.SESSION
response = request.RESPONSE

def calculateGPA():
    """calculate the gpa"""
    sum = 0
    course_count = 0
    for sc in context.objectValues():
        result = sc.getContent()
        if not result.grade:
            continue
        res = context.portal_catalog({'meta_type': 'Course',
                                      'id': sc.aq_parent.id})
        if len(res) < 1:
            continue
        course = res[0].getObject().getContent()
    if course_count:
        return sum/course_count
    return 0.0

def cmp_semester_id(a,b):
    s1 = "%(semester)s%(id)s" % a
    s2 = "%(semester)s%(id)s" % b
    if s1 == s2:
        return 0
    if s1 > s2:
        return 1
    return -1

student_id = context.getStudentId()

info = {}
info['is_so'] = is_so = context.isSectionOfficer()
info['is_student'] = is_student = context.isStudent()
info['is_ca'] = is_ca = context.isCourseAdviser()
info['student'] = student = context.students_catalog(id=student_id)[0]
info['review_state'] = review_state = context.getStudentReviewState()
info['view_only'] =  review_state != "school_fee_paid"
info['show_check_boxes'] =  (is_ca and review_state in ('school_fee_paid',)) or\
                            (is_student and context.getStudentReviewState() == "school_fee_paid") or\
                            (is_so)
info['choosen_ids'] = request.get('ids',[])
info['status_info'] = ""
if is_student:
    if review_state == 'courses_registered':
        info['status_info'] = "Request for Course Validation pending"
    elif review_state == 'courses_validated':
        info['status_info'] = "Courses validated"
elif is_ca:
    if review_state == 'courses_registered':
        info['status_info'] = "Please validate these Courses"
    elif review_state == 'courses_validated':
        info['status_info'] = "Courses validated"
info['doc'] = context.getContent()
##study_course = context.aq_parent.getContent()
##cert_id = study_course.study_course
cert_id = student.course
info['cert_id'] = cert_id
normal = []
carry_overs = []
credits_total = 0
for id,obj in context.objectItems():
    #try:
    #    credit = int(obj.getContent().credits)
    #except ValueError:
    #    credit = 3
    #credits_total += credit
    if not id:
        continue
    if id.endswith('_co'):
        d = context.getCourseInfo(id[:-3])
        try:
            credits_total += int(d['credits'])
        except ValueError:
            credits_total += 0
        d['id'] = id
        d['grade'] = obj.getContent().grade
        carry_overs.append(d)
    else:
        d = context.getCourseInfo(id)
        d['id'] = id
        coe = getattr(obj.getContent(),'core_or_elective',True)
        d['coe'] = 'Core'
        try:
            credits_total += int(d['credits'])
        except ValueError:
            credits_total += 0
        if not coe:
            d['coe'] = 'Elective'
        normal.append(d)
info['credits_total'] = credits_total
max_credits = 50
if context.getId() == student.end_level:
    max_credits = 51
info['max_credits'] = max_credits
info['credits_exceeded'] = credits_total > max_credits
current_session = student.session
info['submission_allowed']= not info['credits_exceeded'] and current_session == context.getSessionId()[-2:]
carry_overs.sort(cmp_semester_id)
info['carry_overs'] = carry_overs
normal.sort(cmp_semester_id)
info['normal'] = normal

students_object = context.portal_url.getPortalObject().campus.students
student = getattr(students_object, student_id)
info['app'] = student.application
info['app_doc'] = student.application.getContent()

return info

