/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package templates;

import common.RegistroBase;
import exception.CompileException;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.antlr.v4.runtime.TokenStream;
import org.antlr.v4.runtime.tree.ParseTreeWalker;

/**
 *
 * @author EUGENIO CARVALHO
 */
public class RenderStmt {

    protected ParseTreeWalker walker;
    protected TemplateParser.InitContext tree;
    public final String ID;
    private final String Format;

    RenderStmt(String id, String format) {
        ID = id;
        Format = format;
        ANTLRInputStream input = new ANTLRInputStream(Format);
        TemplateLexer lexer = new TemplateLexer(input);
        lexer.removeErrorListeners();

        CommonTokenStream tokens = new CommonTokenStream(lexer);
        TemplateParser parser = new TemplateParser((TokenStream) tokens);

        parser.removeErrorListeners();
        tree = parser.init();
        walker = new ParseTreeWalker();
    }

    public String Render(RegistroBase ctx) throws CompileException {
//        System.out.println("ctx:" + ctx);
//        throw new Exception("assssssssssss");
        TListener listener = new TListener(ctx);
        walker.walk(listener, tree);
        if (listener.hasError()) {
//            System.out.println("ctx:" + ctx);

            throw new CompileException(
                    "Render: %s\nFormat: %s)\nError: %s",
                    ID,
                    Format,
                    //                    ctx.Get("block.position"),
                    listener.GetError()
            );
        }
        return listener.toString();
    }
}
