package com.njzscloud.common.gen.support;

import lombok.extern.slf4j.Slf4j;
import org.beetl.core.Configuration;
import org.beetl.core.GroupTemplate;
import org.beetl.core.Template;
import org.beetl.core.resource.MapResourceLoader;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

@Slf4j
public class TemplateEngine {

    private static final GroupTemplate GT;
    private static final MapResourceLoader LOADER = new MapResourceLoader();
    private static final Map<String, TemplateEngine> ENGINE = new ConcurrentHashMap<>();

    static {
        GroupTemplate getTemplate_;
        try {
            Configuration cfg = Configuration.defaultConfiguration();
            getTemplate_ = new GroupTemplate(LOADER, cfg);
            getTemplate_.registerFunction("toCamelCase", Btl.toCamelCase);
            getTemplate_.registerFunction("upperFirst", Btl.upperFirst);
            getTemplate_.registerFunction("isBlank", Btl.isBlank);
            getTemplate_.registerFunction("subAfter", Btl.subAfter);
            getTemplate_.registerFunction("sqlDataTypeMap", Btl.sqlDataTypeMap);
        } catch (IOException e) {
            getTemplate_ = null;
            log.error("模板引擎初始化失败", e);
        }
        GT = getTemplate_;
    }

    private final String tplName;

    private TemplateEngine(String tplName, Tpl tpl) {
        this.tplName = tplName;
        LOADER.put(tplName + "-content", tpl.getContent());
        LOADER.put(tplName + "-dir", tpl.getDir());
        LOADER.put(tplName + "-filename", tpl.getFilename());
    }

    public static TemplateEngine getEngine(String tplName, Tpl tpl) {
        return ENGINE.computeIfAbsent(tplName, key -> new TemplateEngine(tplName, tpl));
    }

    public static void rmEngine(String tplName) {
        ENGINE.remove(tplName);
        LOADER.remove(tplName + "-content");
        LOADER.remove(tplName + "-dir");
        LOADER.remove(tplName + "-filename");
    }

    public String render(String tplName, Map<String, Object> data) {
        Template template = GT.getTemplate(tplName);
        template.binding(data);
        return template.render();
    }

    public String renderContent(Map<String, Object> data) {
        return render(tplName + "-content", data);
    }

    public String renderDir(Map<String, Object> data) {
        return render(tplName + "-dir", data);
    }

    public String renderFilename(Map<String, Object> data) {
        return render(tplName + "-filename", data);
    }
}
