package com.qmth.boot.tools.freemarker;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

import java.io.StringWriter;
import java.nio.charset.StandardCharsets;
import java.util.WeakHashMap;

/**
 * Freemarker模版工具
 */
public class FreemarkerUtil {

    private static Configuration configuration;

    private static WeakHashMap<String, Template> templateMap = new WeakHashMap<>();

    private static Configuration getConfiguration() {
        if (configuration == null) {
            configuration = new Configuration(Configuration.VERSION_2_3_32);
            configuration.setDefaultEncoding(StandardCharsets.UTF_8.name());
            configuration.setLogTemplateExceptions(false);
            configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
        }
        return configuration;
    }

    /**
     * 使用数据对象按表达式取值
     *
     * @param expression freemarker格式表达式，如${key}
     * @param data       数据对象
     * @return
     */
    public static String getValue(String expression, Object data) {
        return getValue(expression, data, null);
    }

    /**
     * 使用数据对象按表达式取值
     *
     * @param expression freemarker格式表达式，如${key}
     * @param data       数据对象
     * @param fallback   异常返回值，为null则抛出过程异常
     * @return
     */
    public static String getValue(String expression, Object data, String fallback) {
        try {
            Template template = templateMap.get(expression);
            if (template == null) {
                template = new Template(expression, expression, getConfiguration());
                templateMap.put(expression, template);
            }
            StringWriter writer = new StringWriter();
            template.process(data, writer);
            return writer.toString();
        } catch (Exception e) {
            if (fallback != null) {
                return fallback;
            } else {
                throw new RuntimeException("Freemarker value generate error", e);
            }
        }
    }
}
