from io import StringIO

from antlr4.error.ErrorListener import ErrorListener


class MINTErrorListener(ErrorListener):
    """Error listener that will fire all error messages

    Listens to the errors and formats the output in a user readable manner
    """

    def __init__(self, output: StringIO):
        """Constructor

        Args:
            output (StringIO): IO stream object where the output is supposed to be
            written to
        """
        super().__init__()
        self.output = output
        self._symbol = ""
        self.pass_through = True

    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
        """Writes the syntax error to the listener output

        Args:
            recognizer ([type]): ANTLR internal
            offendingSymbol ([type]): Symbol which caused the error
            line ([type]): Line number
            column ([type]): Column number
            msg ([type]): Message generated by ANTLR
            e ([type]): ANTLR internal
        """
        self.output.write("Line {}:{} - {}".format(line, column, msg))
        self._symbol = offendingSymbol.text
        self.pass_through = False

    @property
    def symbol(self):
        """Symbol associated with the current error

        Returns:
            [String]: Error symbol
        """
        return self._symbol
