from antlr4 import *
from CLexer import CLexer
from CParser import CParser
from CListener import CListener
# import re

# az koja befahmim ke in ExpressionStatement hayi ke peyda kardim tu if ya for hastan?

def main():
    file = FileStream("gzunBm.c")
    # file = FileStream("RXP.c")
    lexer = CLexer(file)
    stream = CommonTokenStream(lexer)
    parser = CParser(stream)
    tree = parser.compilationUnit()

    listener = myCListener()
    walker = ParseTreeWalker()
    walker.walk(listener, tree)

    listener.show()


class myCListener(CListener):

    def __init__(self):
        self.is_main = True
        self.variable = {}
        self.parameter = []
        self.function_name = ""

    def enterFunctionDefinition(self, ctx:CParser.FunctionDefinitionContext):
        # if self.is_main:
        # function_name = ctx.children.get(1).getChild(0).getChild(0).getText()
        function_name = ctx.children[1].getChild(0).getChild(0).getText()
        if function_name == "main":
            self.is_main = False
            return
        self.function_name = function_name
        print("Function name: " + self.function_name)

    def enterParameterDeclaration(self, ctx:CParser.ParameterDeclarationContext):
        if self.is_main:
            self.parameter.append(ctx.declarator().getText())

    def enterInitDeclarator(self, ctx:CParser.InitDeclaratorContext):
        if self.is_main:
            variable_name = ctx.declarator().getText()
            variable_value = ctx.initializer().getText()
            self.variable[variable_name] = variable_value

    def enterExpressionStatement(self, ctx:CParser.ExpressionStatementContext):
        expr = ctx.getText()
        if self.is_main:
            # expr = ctx.getText()
            expr = expr.replace(";", "")
            expr = expr.split("=")
            for i, j in self.variable.items():
                if i in expr[1]:
                    expr[1] = expr[1].replace(i, j)
            self.variable[expr[0]] = expr[1]
            # print(expr[0] + " = " + expr[1])
        else:
            # expr = expr[17:]  OR:
            # expr = re.sub("^printf\(\"%d\"," + "KjZC\(", "", expr) OR:
            expr = expr[expr.index(self.function_name) + len(self.function_name) + 1: -3]
            expr = expr.split(",")
            for i in range(len(expr)):
                self.parameter[i] = {self.parameter[i]: expr[i]}

    # def enterExpression(self, ctx:CParser.ExpressionContext):
    #     if self.is_main:
    #         expr = ctx.getText()
    #         if expr.__contains__("="):
    #             expr = expr.split("=")
    #             for i, j in self.variable.items():
    #                 if i in expr[1]:
    #                     expr[1] = expr[1].replace(i, j)
    #             self.variable[expr[0]] = expr[1]
    #             print(expr[0] + " = " + expr[1])
    #         else:
    #             print(expr)

    def enterSelectionStatement(self, ctx:CParser.SelectionStatementContext):
        # if ( condition ) statement else statement
        # condition:
        print(ctx.children[2].getText())
        # statement:
        print(ctx.children[4].getText())
        # else:
        # print(ctx.children[5].getText())
        # statement:
        print(ctx.children[6].getText())

    def enterIterationStatement(self, ctx:CParser.IterationStatementContext):
        # print(ctx.children[2].getText())
        for_condition = ctx.children[2].getText().split(";")
        print(for_condition)
        print("IterationStatement: " + ctx.children[4].getText())

    def show(self):
        # print("Variable:")
        # for i,j in self.variable.items():
        #     print(i + ": " + j)
        print("\nParameter:")
        for i in self.parameter:
            print(i)


if __name__ == '__main__':
    main()

# s = "printf('%d',KjZC(711,-287,123,857));"
# print(s.index("KjZC"))
# print(s[12:])
# print(s[s.index("KjZC"):])
# print(s[s.index("KjZC") + len("KjZC") + 1:])
# x = s[s.index("KjZC") + len("KjZC") + 1:]
# print(x[:-3])
# print(re.sub("\)\);", "", x))
# print(s)
# print(s[2:])
# print(s[:2])
# print(s[-2:])
# print(s[:-3])
# x = "The fat cat sat on the mat."
# print(x)
# print(re.sub("the", "", x))
# print(re.sub("^printf\('%d',*\)\);", "", s))
# print(re.sub("^printf\('%d'," + "KjZC\(", "", s))
