package org.bdware.sc.visitor;

import org.antlr.v4.runtime.misc.Interval;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bdware.sc.node.AnnotationNode;
import org.bdware.sc.node.InterfaceNode;
import org.bdware.sc.parser.YJSParser.AnnotationContext;
import org.bdware.sc.parser.YJSParser.AnnotationLiteralContext;
import org.bdware.sc.parser.YJSParser.InterfaceDeclarationContext;
import org.bdware.sc.parser.YJSParserBaseVisitor;

import java.util.ArrayList;
import java.util.List;

public class InterfaceReader extends YJSParserBaseVisitor<InterfaceNode> {
    private static final Logger LOGGER = LogManager.getLogger(InterfaceReader.class);
    InterfaceNode node;
    String fileName;
    // Stack<String> regStack;
    int regID;

    public InterfaceReader(String fileName) {
        this.fileName = fileName;
    }

    @Override
    public InterfaceNode visitInterfaceDeclaration(InterfaceDeclarationContext ctx) {
        node = new InterfaceNode(ctx.Identifier().toString(), fileName);

        node.setLine(ctx.start.getLine());
        node.setPos(ctx.start.getCharPositionInLine());

        node.setInterval(
                new Interval(ctx.Interface().getSourceInterval().a, ctx.getSourceInterval().b));

        List<AnnotationContext> annotations = new ArrayList<>();
        if (null != ctx.annotations()) {
            annotations = ctx.annotations().annotation();
        }
        for (AnnotationContext annotation : annotations) {
            AnnotationNode annNode = new AnnotationNode(annotation.Identifier().toString());
            if (null != annotation.annotationArgs())
                for (AnnotationLiteralContext tNode : annotation.annotationArgs()
                        .annotationLiteral()) {
                    if (null != tNode.numericLiteral()) {
                        annNode.addArg(tNode.numericLiteral().getText());
                        LOGGER.debug(
                                "------AnnotationNumericArgs:" + tNode.numericLiteral().getText());
                    } else if (null != tNode.StringLiteral()) {
                        annNode.addArg(tNode.StringLiteral().getText());
                        LOGGER.debug(
                                "------AnnotationStringArgs:" + tNode.StringLiteral().getText());
                    } else {
                        annNode.addArg(tNode.objectLiteral().getText());
                        LOGGER.debug(
                                "------AnnotationObjectArgs:" + tNode.objectLiteral().getText());
                    }
                }
            node.addAnnotation(annNode);
        }
        return node;
    }
}
