package tech.easyflow.system.config;

import tech.easyflow.common.util.SpringContextUtil;
import tech.easyflow.common.dict.DictManager;
import tech.easyflow.system.entity.SysDict;
import tech.easyflow.system.service.SysDictService;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.EventListener;

import java.util.List;

/**
 * 注册由字典表维护的静态业务字典。
 */
@Configuration
public class SysDictAutoConfig {

    private final SysDictService service;

    /**
     * 创建系统字典自动配置。
     *
     * @param service 系统字典服务
     */
    public SysDictAutoConfig(SysDictService service) {
        this.service = service;
    }

    /**
     * 应用启动完成后注册静态字典。
     */
    @EventListener(ApplicationReadyEvent.class)
    public void onApplicationStartup() {

        DictManager dictManager = SpringContextUtil.getBean(DictManager.class);
        List<SysDict> sysDicts = service.list();
        if (sysDicts != null) {
            sysDicts.forEach(sysDict -> dictManager.putLoader(sysDict.buildLoader()));
        }
    }
}
