## 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 2760 2007-11-26 07:39:15Z henrik $
"""
return Info about the Studylevel
try:
    from Products.zdb import set_trace
except:
    def set_trace():
        pass
"""

import DateTime

info = context.waeup_tool.getAccessInfo(context)
student_id = info['student_id']
if student_id is None:
    return None

mtool = context.portal_membership
pprops = context.portal_properties
member = mtool.getAuthenticatedMember()
member_id = str(member)

course_results = context.course_results
request = context.REQUEST
response = request.RESPONSE
import logging
logger = logging.getLogger('Skins.getStudyLevelInfo')

level_id  =  context.getId()
level_doc = info['doc'] = context.getContent()

info['is_so'] = is_so = info['is_sectionofficer']
#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['student'] = student = context.students_catalog.getRecordByKey(student_id)
info['review_state'] = review_state = student.review_state
is_current_level = level_id == student.level
school_fee_paid =  review_state == 'school_fee_paid'
info['is_current_level'] = is_current_level
info['has_verdict'] = has_verdict = level_doc.verdict

info['submission_allowed']= school_fee_paid and is_current_level and not has_verdict
info['validation_allowed']= review_state == 'courses_registered' and is_current_level
info['rejection_allowed']= review_state in ('courses_registered', 'courses_validated',) and is_current_level
info['validated'] = review_state == 'courses_validated' and is_current_level

info['show_check_boxes'] =  (is_ca and school_fee_paid and is_current_level and not has_verdict) or\
                            (info['is_student'] and school_fee_paid and is_current_level and not has_verdict) or\
                            (is_so and is_current_level and not has_verdict)

info['verdict'] = context.portal_vocabularies.verdicts.get(level_doc.verdict).upper()
info['session'] = context.portal_vocabularies.sessions.get(level_doc.session)
info['level_str'] = context.portal_vocabularies.student_levels.get(level_id)

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"

cert_id = student.course
info['cert_id'] = cert_id
total_credits,gpa,carry_overs,normal1,normal2,normal3 = course_results.getCourses(student_id,level_id)
info['total_credits'] = total_credits

#start customization



max_credits = 100
info['without_score'] = False
info['without_cascore'] = False

items = []
subobjects = context.objectValues()
for subobject in subobjects:
    row = {}
    row['id'] = subobject.getId()
    row['title'] = '%s' % context.portal_vocabularies.terms.get(subobject.getId())
    items.append(row)
info['items'] = items

complete1 = 0
score_calc_average_1 = 0
for r in normal1:
    if r['grade'] and r['atl']:
        complete1 += 1
        score_calc_average_1 += r['score_calc']
if len(normal1) == complete1:
    complete1 =  True
else:
    complete1 = False
if len(normal1):
    score_calc_average_1 /= len(normal1)    
info['complete1'] = complete1     
info['score_calc_average_1'] = '%.2f' % score_calc_average_1  

complete2 = 0
score_calc_average_2 = 0
for r in normal2:
    if r['grade'] and r['atl']:
        score_calc_average_2 += r['score_calc']
        complete2 += 1
if len(normal2) == complete2:
    complete2 =  True
else:
    complete2 = False
if len(normal2):
    score_calc_average_2 /= len(normal2)
info['complete2'] = complete2
info['score_calc_average_2'] = '%.2f' % score_calc_average_2  

complete3 = 0
score_calc_average_3 = 0
for r in normal3:
    if r['grade'] and r['atl']:
        complete3 += 1
        score_calc_average_3 += r['score_calc']
if len(normal3) == complete3:
    complete3 =  True
else:
    complete3 = False
if len(normal3):
    score_calc_average_3 /= len(normal3)    
info['complete3'] = complete3
info['score_calc_average_3'] =  '%.2f' % score_calc_average_3  

terms_completed = bool(score_calc_average_1) + bool(score_calc_average_2) + bool(score_calc_average_3)

if terms_completed:
    score_calc_average_cum = (score_calc_average_1 + score_calc_average_2 + score_calc_average_3)/terms_completed
else:
    score_calc_average_cum = 0 

info['score_calc_average_cum'] = '%.2f' % score_calc_average_cum

session_id = level_doc.session
yga1,yga2,yga3,counter1,counter2,counter3,yg1,yg2,yg3 = course_results.getYearGroupAverage(session_id,level_id)
info['yga1'] = yga1
info['yga2'] = yga2
info['yga3'] = yga3
info['counter1'] = counter1
info['counter2'] = counter2
info['counter3'] = counter3


#yg1.sort(reverse=True)
#if not len(yg1):
#    pos1 = 'no result'
#for pos1 in range(len(yg1)):
#    if yg1[pos1] <= float(score_calc_average_1):
#        break
#info['pos1'] = '%d of %d' % (pos1+1,len(yg1))

#end customization

info['max_credits'] = max_credits
info['credits_exceeded'] = total_credits > max_credits
current_session = student.session

info['gpa'] = gpa
if gpa and total_credits:
    info['gpa'] = "%4.2f" % (float(gpa)/int(total_credits))

info['carry_overs'] = carry_overs
normal1.sort(cmp=lambda x,y: cmp( x['title'],y['title']))
normal2.sort(cmp=lambda x,y: cmp( x['title'],y['title']))
normal3.sort(cmp=lambda x,y: cmp( x['title'],y['title']))

info['normal1'] = normal1
info['normal2'] = normal2
info['normal3'] = normal3

info['data_missing'] = not info['normal1'] and not info['normal2'] and not info['normal3']
info['spillover'] = student.level > student.end_level

students_object = context.portal_url.getPortalObject().campus.students
student = getattr(students_object, student_id)
info['app'] = student.application
info['app_doc'] = student.application.getContent()

if pprops.session == info['session']:
    info['date1'] = DateTime.DateTime(pprops.date1).strftime('%d/%m/%Y')
    info['date2'] = DateTime.DateTime(pprops.date2).strftime('%d/%m/%Y')
    info['date3'] = DateTime.DateTime(pprops.date3).strftime('%d/%m/%Y')
else:
    info['date1'] = 'n/a'
    info['date2'] = 'n/a'
    info['date3'] = 'n/a'

info['over_pos_term1'] = getattr(level_doc, 'over_pos_term1','n/a')
info['no_stud_term1'] = getattr(level_doc, 'no_stud_term1','n/a')
info['over_pos_term2'] = getattr(level_doc, 'over_pos_term2','n/a')
info['no_stud_term2'] = getattr(level_doc, 'no_stud_term2','n/a')
info['over_pos_term3'] = getattr(level_doc, 'over_pos_term3','n/a')
info['no_stud_term3'] = getattr(level_doc, 'no_stud_term3','n/a')
info['over_pos_cum'] = getattr(level_doc, 'over_pos_cum','n/a')
info['no_stud_cum'] = getattr(level_doc, 'no_stud_cum','n/a')

return info
