# This file parses an input file that has been generated by git blame --line-porcelain
# and outputs a file with the following columns:

# commit,author,committer-time,code

if __name__ == '__main__':
    import argparse
    import datetime

    parser = argparse.ArgumentParser(description='Parse git blame output.')
    parser.add_argument('input', type=argparse.FileType('r', errors='replace'),
                        help='Input file')
    # take in date.txt for the date
    parser.add_argument('date', type=argparse.FileType('r', errors='ignore'),
                        help='Date file')
    parser.add_argument('output', type=argparse.FileType('w+'),
                        help='Output file')
    args = parser.parse_args()

    # read input file
    with args.input as f:
        lines = f.readlines()

    with args.date as f:
        date = f.readlines()

    assert len(date) == 1, "Date file should only have one line."
    compare_date = date[0].strip()

    # parse input file
    commit = ''
    author = ''
    committer_time = ''
    code = ''
    lines_count = 0
    # write output file
    code_seen = False
    with args.output as f_out:
        for line in lines:
            if commit == '':
                commit = line.split(' ')[0].strip()
            elif line.startswith('author '):
                author = line.split(' ')[1].strip()
            elif line.startswith('committer-time '):
                committer_time = line.split(' ')[1].strip()
                # calculate the difference in days between the commit and the date

                # convert to datetime
                commit_date = datetime.datetime.fromtimestamp(int(committer_time))
                date = datetime.datetime.strptime(compare_date, '%Y-%m-%d')

                # calculate the difference
                diff = date - commit_date
                diff = diff.days

                committer_time = str(diff)
            elif line.startswith('\t'):
                code = line.strip()
                code_seen = True # Need this since we can have a line of code that is just a tab (white space changes)
                # get rid of extra quotes
            if commit and author and committer_time and code_seen:
                # write to output file
                f_out.write('{}|{}|{}|{}\n'.format(commit, author, committer_time, code))
                lines_count += 1
                code_seen = False
                # reset variables
                commit = ''
                author = ''
                committer_time = ''
                code = ''

    print("Wrote {} lines for file {}.".format(lines_count, args.input.name))
