import sys, os
from antlr4.error.ErrorListener import *
from antlr4 import *
sys.path.append(os.path.dirname(os.path.abspath(__file__))+'/antlr')
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from CorpusParser import CorpusParser
from CorpusLexer import CorpusLexer
from CorpusEvalVisitor import CorpusEvalVisitor


class CorpusErrorListener(ErrorListener):

    def __init__(self):
        self._message = ''

    def syntaxError(self, recognizer, offendingSymbol, line, column, msg, e):
        if self._message == '':
            self._message = "line " + str(line) + ":" + str(column) + " " + msg

    def getMessage(self):
        return self._message


class CorpusErrorReporter(object):
    def __init__(self, cmd: str):
        input = InputStream(cmd)
        lexer = CorpusLexer(input)
        lexer.removeErrorListeners()
        listener = CorpusErrorListener()
        lexer.addErrorListener(listener)
        stream = CommonTokenStream(lexer)
        parser = CorpusParser(stream)
        parser.removeErrorListeners()
        parser.addErrorListener(listener)

        if cmd.find("author:") == 0 or cmd.find("section:") == 0 or cmd.find("document:") == 0 or cmd.find("dynasty:") == 0:
            parser.field()
        elif cmd.find(':') >= 0:
            parser.prog()
        else:
            parser.expr()
        self._message = listener.getMessage()

    def error(self):
        if self._message == '':
            return False
        return True

    def getMessage(self):
        return self._message


if __name__ == '__main__':
    print(CorpusErrorReporter('可以').getMessage())