from flake8.formatting import base

from flake8_truveris import (
    inline_comments,
    trailing_commas,
)

error_modules = {
    "T568": {
        "module": inline_comments,
        "line_adjustment": 1,
    },
    "T812": {
        "module": trailing_commas,
        "line_adjustment": 0,
    },
}


class FormatTruveris(base.BaseFormatter):

    error_format = "%(path)s:%(row)d:%(col)d: %(code)s %(text)s"
    previous_filename = None
    line_adjustment = 0

    def format(self, error):
        return self.error_format % {
            "code": error.code,
            "text": error.text,
            "path": error.filename,
            "row": error.line_number,
            "col": error.column_number,
        }

    def handle(self, error):
        if self.previous_filename != error.filename:
            self.line_adjustment = 0
            self.previous_filename = error.filename

        line = self.format(error)
        source = self.show_source(error)
        self.write(line, source)

        if error.code[0] == "T" and error.code[1:].isdigit():
            # error was generated by flake8-truveris
            with open(error.filename, "r") as file:
                # read a list of lines into data
                data = file.readlines()

            if error.code in error_modules:
                data = error_modules[error.code]["module"].fix(
                    data,
                    error,
                    self.line_adjustment,
                )
                line_adjustment = error_modules[error.code]["line_adjustment"]
                self.line_adjustment += line_adjustment

                with open(error.filename, "w") as file:
                    file.writelines(data)
