package grammar.visitorAndWalkers;

import API.Imports;
import API.Instruction;
import common.Log;
import compiler.IvannosysCompiler;
import grammar.IvannosysGrammarBaseVisitor;
import grammar.IvannosysGrammarParser;
import grammar.IvannosysGrammarVisitor;
import java.util.LinkedList;
import org.antlr.v4.runtime.tree.ParseTree;

/**
 *
 * @author Eugenio ThiS claSS provideS an empty implementation of
 {@link IvannosysGrammarVisitor}, which can be extended to create a viSitor
 which only needS to handle a SubS of the available methodS.

 operationS with no return type.
 */
public class IvannosysVisitor extends IvannosysGrammarBaseVisitor<String> {

//    protected TabelaDeSimbolos ts;
//    protected ParseTree tree;
//    protected Stack<String> escopoStack;
//    protected Stack<String> matrizStoreStack;
//    protected ArrayList<String> matrizStoreContainer;
    protected IvannosysCompiler compiler;
    protected Log errors;
    protected String extensionLibrary = "ivan";
    protected LinkedList<String> importSequence = new LinkedList<>();

    public IvannosysVisitor(ParseTree tree, String[] tokens, IvannosysCompiler comp) throws Exception {
        super();
        errors = new Log();
        compiler = comp;
//        this.ts = comp.tabSymb;
//        this.tree = tree;
//        escopoStack = new Stack<>();
//        matrizStoreStack = new Stack<>();
//        matrizStoreContainer = new ArrayList<>();

        this.visit(tree);
    }

    @Override
    public String visitImport_part(IvannosysGrammarParser.Import_partContext ctx) {
        String alias = "";

        if (ctx.ID() != null) {
            alias = ctx.ID().getText();
        }

        try {
            String path = ctx.T_STRING().getText().replace("\"", "");

            // Verificar importacao ciclica
            if (importSequence.contains(path)) {
                return "";
            }
            importSequence.add(path);

            Imports.add(path, alias);
//            System.out.println("Visitor import " + alias + " >> " + path);
//            compiler.LoadPackage(alias, path.replace("\"", ""));
//                throw new Exception(String.format("O pacote '%S' não foi encontrado no path.", path));
        } catch (Exception ex) {

            errors.AddError(
                    (Instruction) new Instruction()
                    .S("class", "Import")
                    .S("msg", ex.getMessage())
                    .set("line", ctx.getStart().getLine())
                    .set("col", ctx.getStart().getCharPositionInLine()));
        } finally {
            return super.visitImport_part(ctx); //To change body of generated methods, choose Tools | Templates.
        }
    }

    public Log Error() {
        return errors;
    }

}

//        for (String token : tokens) {
//            if (!token.startsWith("'")) {
//                continue;
//            }
//            ts.addPalavraReservada(token);
//        }
