/*
 * 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 template;

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;
import template.TemplateParser;

/**
 *
 * @author EUGENIO CARVALHO
 */
public class Template implements TPLInterface {

    protected String template;
    protected TemplateParser.InitContext tree;
    protected ParseTreeWalker walker;
    protected TPLInterface tpl;
    protected TemplateCtx gctx;

    public Template(String template, TemplateCtx ctx) {
        this.template = template;
        gctx = ctx;
        Init();
    }

    public Template() {
    }

    protected void Init() {
        ANTLRInputStream input = new ANTLRInputStream(template);
        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 ParseTreeWalker getWalker() {
        return walker;
    }

    public void setWalker(ParseTreeWalker walker) {
        this.walker = walker;
    }

    public String Render(TemplateCtx ctx) {
        TListener listener = new TListener(ctx, gctx);

        walker.walk(listener, tree);

        return listener.toString();
    }

    @Override
    public TPLInterface New(String tpl, TemplateCtx ctx) {
//        System.out.println("new :" + this.getClass().getName());
        return new Template(tpl, ctx);
    }

}
