#!/usr/bin/env python
# -*- coding: utf-8 -*-

import os
import glob
import csv


def mkgrades(gradesfile, pattern, message):
    """
    Get the scores from all files matching [pattern], compute
    the total scores per student (per email) and write them to
    the file [gradesfile]. Prints [message] at the top of the file.
    """
    sfiles = glob.glob(pattern) # get all files of this form
    student = {} # students dictionary, one entry per student which is another dictionary
    for s in sfiles: # for all scores files
        probname = s[7:-4] # get problem name from filename
        f = open(s, "r") # open file for reading
        for x in csv.reader(f): # read the file with csv reader, one row at a time (comma separated values)
            email = x[0]
            grade = 1 if x[1].strip()=='OK' else 0 # 1 for correct program 0 for wrong program
            if email in student:
                student[email][probname] = grade    # email already in global dictionary
                                                    # just add the grade to its dictionary
            else:
                student[email] = {probname: grade}  # add the email to global dict., with the grade
        f.close()
    
    for email in student: # for each student add up the problem scores
        grlist = [student[email][s] for s in student[email]]# student[email] is the students dictionary of grades
                                                            # s traverses all problem names
        student[email]["grade"] = sum(grlist)   # add the grades for the student, add to dictionary with key "grade"
        
    # sort emails
    emails = [x for x in student]
    emails.sort()
    
    # output grades
    f = open(gradesfile, "w")   # open file for writing
    print >>f, message.encode("UTF-8")
    for email in emails:
        print >>f, "%30s\t%2d" % (email, student[email]["grade"])
    f.close()
    
    os.system("chmod ugo+r "+gradesfile)    # make file world readable

# non-examination problems
mkgrades("grades.txt", "scores-[0-9][0-9]*.csv", u"Πόσες ασκήσεις (όχι σε εξέταση) έχετε κάνει σωστά μέχρι στιγμής")
# examination problems
mkgrades("exam-grades.txt", "scores-e[01234]*.csv", u"Πόσες ασκήσεις (σε εξέταση) έχετε κάνει σωστά μέχρι στιγμής")
# harder problems
mkgrades("X-grades.txt", "scores-[0-9][0-9]*X.csv", u"Πόσες ασκήσεις τύπου X έχετε κάνει σωστά μέχρι στιγμής")
