'''
:author: Robin Flume
:contact: robin.flume@rub.de
'''

import re
from pgf.log.logger import Logger
from pgf.analysis.fileparser.abstract_parser import InputParser

class PlaintextWithcount(InputParser):
    ''' Parser for files containing a password counter and the according plaintext password per line.

    :requires: Counter and password must be devided by a single whitespace character:   '   4238 mypassword!'.
    '''

    def __init__(self, pw_file):
        ''' Generator.
        '''
        # Initiate logger
        self.logger = Logger()
        self.logger.basicConfig('DEBUG')                     # set logger level to DEBUG
        
        self.pw_file = pw_file
        
        self.pw_counter = 0              # counter for the amount of passwords in the leak
        self.error_counter = 0           # counter for the errors occuring during the file-parsing
        self.pws_multi = {}              # Dict to store the passwords from the file including an occurence-counter for each password


    def get_filetype(self):
        ''' Return the input type indicator to run the according analysis module and the execution module correctly.
        '''
        return 'plaintext'


    def parse_pw_file(self):
        ''' Parses the passwords (plaintext) from the password leak and analyzes the occurences of the passwords.

        :requires: One password per line in the file.

        :return: (Dict{'occ', 'lookups'}, Int, Int): Dict containing the parsed passwords and a dict of their occurences in the leak ('occ') as well as a counter for the amount of lookups ('lookups') which is used to count the amout of duplicate candidates that might be generated by a guesser.
        The integers are a password counter and a parsing-error counter.
        '''
        self.logger.debug("Start parsing the password file ...")

        counter_re = re.compile('^\s*[0-9]*')
        pw_re = re.compile('^\s*[0-9]*\s')

        f = open(self.pw_file, 'rU')                    # open the password file
        if f is None:
            self.logger.debug("The pw file could not be opened!\nAnalysis closed!")
            exit(-1)            #TODO: check if this is correct/smartest solution?!

        for line in f:
            try:
                self.pw_counter += 1                    # increment counter
                pw = line.replace(pw_re.findall(line)[0], '')[:-1]
                occ = int(counter_re.findall(line)[0].replace(' ', ''))
                self.pws_multi[pw] = {'occ':occ, 'lookups':0}         # add a dict to the dict-entry [pw] with init values 1 and 0
            except:
                self.error_counter += 1                 # silently ignore decode-errors but count it
        f.close()                                       # close the file
        self.logger.debug("Parsing done!")
        return self.pws_multi, self.pw_counter, self.error_counter
