'''
In this module, we will generate a csv report for a given problem id, which
will include information about how students fared with a given problem id

Usage:

from the reporting directory

python -m problem_ids.get_csv_report_by_problem_id <db_name> <problem_id>

Example:

 python -m problem_ids.get_csv_report_by_problem_id body101x i4x://McGillX/Body101x/problem/fd3a83b0c06243b78554b69ad6f65e03


'''
from collections import defaultdict
import sys

from common.base_edx import EdXConnection
from common.generate_csv_report import CSV

db_name = sys.argv[1]
problem_id = sys.argv[2]
connection = EdXConnection(db_name, 'problem_ids')
collection = connection.get_access_to_collection()

if len(sys.argv) < 3:
    usage_message = """
    No problem id given as a command line argument. Please provide a problem_id

    Usage:
    python get_csv_report_by_problem_id.py <db_name> <problem_id>

    """

    sys.stderr.write(usage_message)
    sys.exit(1)

def _generate_name_from_problem_id(problem_id, display_name):
    '''
    Generate name of csv output file from problem id
    '''
    return '_'.join(problem_id.split('/')[3:]) + '_' +''.join(e for e in display_name if e.isalnum()) + '.csv'

cursor = collection['problem_ids'].find({'event.problem_id': problem_id})
display_name = cursor[0]['module']['display_name']
one_record = cursor[0]['event']
problem_ids_keys = sorted(one_record['correct_map'].keys())
problem_ids = []
for key in problem_ids_keys:
    try:
        item = one_record['submission'][key]
        value = item['question']
        problem_ids.append('{0} : {1}'.format(key, value))
    except KeyError:
        problem_ids.append('{0}'.format(key))
result = []
answers = []
for document in cursor:
    answers = []
    for key in sorted(document['event']['correct_map'].keys()):
        #if key in submission_keys:
        try:
            answers.append(document['event']['submission'][key]['answer'])
            #print document['event']['submission'][key]['answer']
        except KeyError:
            answers.append('blank')
            #print 'blank'
    print answers
        #answers.append(document['event']['submission'][key]['answer'])
#answers = [value['answer'] for _, value in sorted(document['event']['submission'].iteritems())]
    result.append([document['username'], document['event']['attempts'], document['module']['display_name'],document['time'], document['event']['success'],
    document['event']['grade'], document['event']['max_grade']] + answers)
csv_report_name = _generate_name_from_problem_id(problem_id, display_name)
output = CSV(result, ['Username', 'Attempt Number', 'Module', 'Time', 'Success', 'Grade Achieved', 'Max Grade'] + problem_ids, output_file=csv_report_name)
output.generate_csv()

@@ -259,16 +259,32 @@
 blem_id%3E
+ %5B--max-attempt%5D
 %0A%0AExampl
@@ -422,54 +422,49 @@
 '''%0A
-from collections import defaultdict%0Aimport sys
+import sys%0A%0Afrom itertools import groupby
 %0A%0Afr
@@ -551,158 +551,8 @@
 SV%0A%0A
-db_name = sys.argv%5B1%5D%0Aproblem_id = sys.argv%5B2%5D%0Aconnection = EdXConnection(db_name, 'problem_ids')%0Acollection = connection.get_access_to_collection()%0A%0A
 if l
@@ -750,16 +750,32 @@
 blem_id%3E
+ %5B--max-attempt%5D
 %0A%0A    %22%22
@@ -830,16 +830,219 @@
 xit(1)%0A%0A
+db_name = sys.argv%5B1%5D%0Aproblem_id = sys.argv%5B2%5D%0Amax_attempt = True if len(sys.argv) == 4  else False%0Aconnection = EdXConnection(db_name, 'problem_ids')%0Acollection = connection.get_access_to_collection()%0A%0A
 def _gen
@@ -1102,21 +1102,16 @@
 %0A    '''
-%0A    
 Generate
@@ -1150,21 +1150,16 @@
 oblem id
-%0A    
 '''%0A    
@@ -1165,16 +1165,17 @@
  return 
+(
 '_'.join
@@ -1209,16 +1209,29 @@
  + '_' +
+%0A            
 ''.join(
@@ -1278,16 +1278,17 @@
 + '.csv'
+)
 %0A%0Acursor
@@ -1769,29 +1769,16 @@
 lt = %5B%5D%0A
-answers = %5B%5D%0A
 for docu
@@ -1878,44 +1878,8 @@
 )):%0A
-        #if key in submission_keys:%0A
     
@@ -1974,340 +1974,55 @@
     
-    #print document%5B'event'%5D%5B'submission'%5D%5Bkey%5D%5B'answer'%5D%0A        except KeyError:%0A            answers.append('blank')%0A            #print 'blank'%0A    print answers%0A        #answers.append(document%5B'event'%5D%5B'submission'%5D%5Bkey%5D%5B'answer'%5D)%0A#answers = %5Bvalue%5B'answer'%5D for _, value in sorted(document%5B'event'%5D%5B'submission'%5D.iteritems())%5D
+except KeyError:%0A            answers.append('')
 %0A   
@@ -2089,16 +2089,35 @@
 empts'%5D,
+%0A                  
  documen
@@ -2157,24 +2157,43 @@
 ent%5B'time'%5D,
+%0A                  
  document%5B'e
@@ -2207,24 +2207,39 @@
 'success'%5D,%0A
+               
     document
@@ -2293,19 +2293,169 @@
 e'%5D%5D
- + answers)
+%0A                   + answers)%0A%0Aif max_attempt:%0A    result = %5Bmax(items, key=lambda x : x%5B1%5D) for key, items in%0A              groupby(result, lambda x : x%5B0%5D)%5D %0A
 %0Acsv
@@ -2546,16 +2546,29 @@
 (result,
+%0A            
  %5B'Usern
@@ -2665,16 +2665,29 @@
 lem_ids,
+%0A            
  output_

Add option to only include latest attempts by student