#!/usr/bin/env python
import fileinput
import pprint
import re
import subprocess
from sortedcontainers import SortedDict

# Create an empty dictionary to store all our warning information.
warnings = {}

# Loop over the lines of the build output.
for line in fileinput.input():

    # Strip out the first eight characters.  These are control characters that
    # switch on bold faced text.
    line = line[8:]

    # This script only works on unused parameter warnings.
    if "-Wunused-parameter" in line:

        # The line should have the following form:
        # filename:row:col: warning: specifics
        pieces = line.split(":")
        filename = pieces[0]
        row = int(pieces[1])
        col = int(pieces[2])
        rest = pieces[-1]

        # The parameter name appears within ‘these quotes’.  We need to
        # strip off leading and trailing control characters.
        parameter = re.search("‘(.*)’", rest).group(1)[8:-6]

        # Our warnings dictionary has the following structure:
        # warnings = {
        #   filename: {
        #     row: SortedDict{
        #       col: parameter
        #     }
        #   }
        # }
        if filename in warnings:
            if row in warnings[filename]:
                warnings[filename][row][col] = parameter
            else:
                warnings[filename][row] = SortedDict({col: parameter})
        else:
            warnings[filename] = {row: SortedDict({col: parameter})}
#pp = pprint.PrettyPrinter(indent=4, compact=True)
#pp.pprint(warnings)
for (filename, data) in warnings.items():
    lineNumber = 1
    for line in fileinput.input(filename, inplace=True):
        if lineNumber in data:
            for (row, stuff) in data.items():
                if lineNumber == row:
                    for (i, (col, parameter)) in enumerate(stuff.items()):
                        col += i * 6
                        start = line.rfind(parameter, 0, col + len(parameter))
                        if line[start - 1] == "*":
                            line = line[:start] + " /* " + line[start:]
                            stop = start + len(parameter) + 4
                        else:
                            line = line[:start] + "/* " + line[start:]
                            stop = start + len(parameter) + 3
                        line = line[:stop] + " */" + line[stop:]
                    print(line, end="")
        else:
            print(line, end="")
        lineNumber += 1

# What about when Type param = defaultValue spans two lines?  col points to
# defaultValue, but the first comment mark needs to be inserted in the prior
# line.

# Sometimes you can have the same warning but the paths to the file are
# different, as in /path/to/file vs /path/to/somewhere/../file, and this messes
# things up because the script tries to comment out the parameter multiple
# times.
