


package com.jwipc.log.logic;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import freemarker.template.Configuration;
import freemarker.template.Template;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * <p> </p>
 *
 * @author BOGON
 * @version 1.0
 * @since JDK 1.8
 */
public class FreeMarkers {
    public static String renderString(String templateString, Map<String, ?> model) {
        if (StrUtil.isEmpty(templateString) && MapUtil.isNotEmpty(model)) {
            Map<String, Object> tmp = new HashMap<>();
            for (String s : model.keySet()) {
                if (Objects.nonNull(model.get(s)) &&
                        !model.get(s).getClass().getName().equals("org.apache.catalina.connector.ResponseFacade")) {
                    tmp.put(s, model.get(s));
                }
            }
            return JSON.toJSONString(tmp);
        } else if (StrUtil.isEmpty(templateString) && MapUtil.isEmpty(model)) {
            return StrUtil.EMPTY;
        } else {
            try {
                StringWriter result = new StringWriter();
                Template t = new Template("name", new StringReader(templateString),
                        new Configuration(Configuration.DEFAULT_INCOMPATIBLE_IMPROVEMENTS));
                t.process(model, result);
                return result.toString();
            } catch (Exception e) {
                e.printStackTrace();
            }
            return StrUtil.EMPTY;
        }
    }
}
