#!/usr/bin/python
# -*- coding: utf-8 -*-
# Author: pollen@cs.wisc.edu (Feel free to email with questions)
# Usage: p?_process_recompile <userid1> <userid2> ...
#    The submissions of the supplied user IDs will be compiled and tested.

import os
import os.path as path
import imp
import sys
import subprocess
import re

# Import grading library.
sys.path.append('/p/course/cs302/public/html/programs/common/py-lib')
import grading

PROGRAM = 'p4'

students = sys.argv
students.pop(0) # Remove the name of this script from argv
studentDirs = grading.compileStudents(
    program= PROGRAM,
    students= students,
    resources= [
      '/p/course/cs302/public/html/programs/%s/grading/resources/build.xml' % PROGRAM
    ])

for studentDir in studentDirs:
  studentName = path.basename(studentDir)
  
  # compileStudents already invoked ant, which ran all the tests.
  print (" Tests finished. Check out the results in report.html (or failures.log) " +
          "and report-ec.html (or failures-ec.log).")
          
  # Check for characters over the max. To do this, we must iterate over all the
  # .java files in the student's directory.
  overages = {}
  for child in os.listdir(studentDir):
    if child.endswith('.java'):
      childPath = path.join(studentDir, child)
      over = grading.countOverColumns(childPath, maxCols=80,
          # Use 3 here instead of 4 to give students a little mercy when
          # indenting is heavy.
          tabWidth=3)
      if over > 30:
        overages[child] = over
  
  # Now we have a list of files that had lines that were too long. Print this
  # result out to the console and to a file.
  if len(overages) > 0:
    message = '  80-CHARACTER RULE NOT FOLLOWED:\n'
    for fileOver in overages:
      message += '     {0}/{1} has {2} characters over the limit.\n'.format(
          studentName, fileOver, overages[fileOver])
    message += ('  Mark the "Use shorter line lengths" item in the "Style ' +
                  'and Structure" section.')
    print (message)

    # Log the message to a file so the TA can look at it later.
    filename = '80-Column-Violation.log'
    f = open(os.path.join(studentDir, filename), 'w')
    f.write(message + "\n")
    f.close()
    
    print ("  This fact has also been logged in the file '" + filename
        + "' in the student's grading directory.")
