package cn.reghao.tnb.auth.app.template;

import com.google.common.collect.Maps;
import freemarker.template.Configuration;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Component;

import jakarta.annotation.PostConstruct;
import java.util.HashMap;
import java.util.Map;

/**
 * @author : langhsu
 * @since 3.0
 */
@Slf4j
@Component
@EnableAsync
public class FreeMarkerConfig {
    @Autowired
    private Configuration configuration;
    @Autowired
    private ApplicationContext applicationContext;

    @PostConstruct
    public void setSharedVariable() {
        Map<String, Object> vars = Maps.newHashMap();
        Map<String, TemplateDirective> map = applicationContext.getBeansOfType(TemplateDirective.class);
        map.forEach((k, v) -> {
            String name = v.getName();
            if (name.indexOf(".") > 0) {
                String[] names = name.split("\\.");
                Map<String, Object> child = (Map<String, Object>) vars.computeIfAbsent(names[0], key -> new HashMap<>());
                child.put(names[1], v);
            } else {
                vars.put(v.getName(), v);
            }
        });

        try {
            configuration.setSharedVariables(vars);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
}
