'''
This module counts the number of navigation events: seq_next, seq_prev, seq_goto
for those students who completed the course
'''

import csv

from base_edx import EdXConnection

connection = EdXConnection('tracking')
collection = connection.get_access_to_collection()

with open('csv_files/McGillX_CHEM181x_1T2014_grade_report_2014-04-24-1030.csv', 'r') as csv_file:
    reader = csv.reader(csv_file)
    usernames = [row[2] for row in reader]


cursor = collection['tracking'].aggregate([{"$match" : {"event_source" : "browser", "$or" : [{"event_type" : "seq_prev"},{"event_type" : "seq_goto"},{"event_type" : "seq_next"}], 'username' : {'$in' : usernames}}}, {"$group" : {"_id" : {'chapter_name' : "$parent_data.chapter_display_name", "display_name" :  "$metadata.display_name", "event_type"  : "$event_type", "event_old" : "$event.old", "event_new" : "$event.new"}, "count" : {"$sum" : 1}}}])

with open('csv_files/navigation_frequency_completers.csv', 'w') as csv_file:
    writer = csv.writer(csv_file)
    writer.writerow(['Chapter Name', 'Display Name', 'Event Type', 'Event Old', 'Event New', 'Count'])
    for item in cursor['result']:
        try:
            writer.writerow([item['_id']['chapter_name'], item['_id']['display_name'], item['_id']['event_type'], item['_id'].get('event_old', 0), item['_id']['event_new'], item['count']])
        except:
           pass 

@@ -173,16 +173,52 @@
 nnection
+%0Afrom generate_csv_report import CSV
 %0A%0Aconnec
@@ -247,16 +247,25 @@
 tracking
+_atoc185x
 ')%0Acolle
@@ -517,16 +517,25 @@
 tracking
+_atoc185x
 '%5D.aggre
@@ -948,16 +948,17 @@
 1%7D%7D%7D%5D)%0A%0A
+#
 with ope
@@ -1022,24 +1022,25 @@
 s csv_file:%0A
+#
     writer =
@@ -1057,24 +1057,25 @@
 r(csv_file)%0A
+#
     writer.w
@@ -1165,16 +1165,17 @@
 ount'%5D)%0A
+#
     for 
@@ -1200,16 +1200,17 @@
 sult'%5D:%0A
+#
         
@@ -1214,16 +1214,17 @@
    try:%0A
+#
         
@@ -1404,16 +1404,17 @@
 unt'%5D%5D)%0A
+#
         
@@ -1421,16 +1421,17 @@
 except:%0A
+#
         
@@ -1439,8 +1439,450 @@
   pass %0A
+%0Aresult = %5B%5D%0Afor item in cursor%5B'result'%5D:%0A    try:%0A        result.append(%5Bitem%5B'_id'%5D%5B'chapter_name'%5D, item%5B'_id'%5D%5B'display_name'%5D, item%5B'_id'%5D%5B'event_type'%5D, item%5B'_id'%5D.get('event_old', 0), item%5B'_id'%5D%5B'event_new'%5D, ite    m%5B'count'%5D%5D)%0A    except:%0A        pass%0A%0Aoutput = CSV(result, %5B'Chapter Name', 'Display Name', 'Event Type', 'Event Old', 'Event New', 'Count'%5D, output_file='navigation_frequency_completers.csv')%0Aoutput.generate_csv()%0A

Update reporting_scripts/navigational_events_completers.py