'''
Created on 03.02.2016

@author: fabian
'''
import os
import collections
import csv

class ResultParser(object):
    '''
    classdocs
    '''


    def __init__(self, resultFolder):
        '''
        Constructor
        '''
        self.resultFolder = resultFolder
        
    
    def getAllCommitsWithJacocoErrors(self):
        commitsWithJacocoErrors = []
        for commit in self.getImmediateSubdirectories(self.resultFolder):
            errorFile = self.resultFolder+"/"+commit+"/jacoco_errors.txt"
            if(os.path.exists(errorFile) and os.path.isfile(errorFile)):
                commitsWithJacocoErrors.append(commit)
                
        return commitsWithJacocoErrors
        
        
    def getAllCommitsWithPitErrors(self):
        commitsWithPitErrors = []
        for commit in self.getImmediateSubdirectories(self.resultFolder):
            errorFile = self.resultFolder+"/"+commit+"/pit_errors.txt"
            if(os.path.exists(errorFile) and os.path.isfile(errorFile)):
                

                
        return commitsWithPitErrors
        
    def createCSVFile(self, outputFile):
        jacocoErrors = self.getAllCommitsWithJacocoErrors()
        pitErrors = self.getAllCommitsWithPitErrors()
        
        result = {}
        for commit in self.getImmediateSubdirectories(self.resultFolder):
            if(not os.listdir(self.resultFolder+"/"+commit) == []):
                parts = commit.split("-")
                result[int(parts[0])] = {'hash': parts[1],'jacocoError' : (commit in jacocoErrors), 'pitError' : (commit in pitErrors)}
                
        sortedResults = collections.OrderedDict(sorted(result.items()))
        
        writer = csv.writer(open(outputFile, 'w'))
        writer.writerow(['Number', 'Hash', 'HasJacocoError', 'HasPitError'])
        for key, value in sortedResults.items():
            writer.writerow([key, value['hash'], value['jacocoError'], value['pitError']])
        
    def getImmediateSubdirectories(self, a_dir):
        """ Helper method, which gets the **immediate** subdirectoriesof a path. Is helpful, if one want to create a 
        parser, which looks if certain folders are there.
        
        :param a_dir: directory from which **immediate** subdirectories should be listed """
        return [name for name in os.listdir(a_dir)
            if os.path.isdir(os.path.join(a_dir, name))]
        
        
if __name__ == "__main__":
    #resultParser = ResultParser("/home/fabian/Arbeit/testEvolution/results/checkstyle")
    #print(resultParser.getAllCommitsWithJacocoErrors())
    #resultParser.createCSVFile("/home/fabian/test.csv")
    
    
    with open("/home/fabian/Arbeit/testEvolution/tmp/checkstyle_working/src/checkstyle/com/puppycrawl/tools/checkstyle/gui/ParseTreeInfoPanel.java", "rb") as sourceFile:
        data = sourceFile.readlines()
    sourceFile.close()
    
    
commitsWithPitErrors.append(commit)