package com.yvan.spring;

import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.io.DefaultResourceLoader;
import org.springframework.core.io.ResourceLoader;

import java.util.List;


@Slf4j
public class DsfConfigurableInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    private final List<String> logbackConfigs = Lists.newArrayList();
    private final ResourceLoader resourceLoader;
    private final String appName;

    public DsfConfigurableInitializer(String appName) {
        this.resourceLoader = new DefaultResourceLoader();
        this.appName = appName;
    }

    //添加 logback 的配置文件路径
    public void addLogbackConfig(String location) {
        if (!Strings.isNullOrEmpty(location)) {
            log.info("load-logback-config=" + location);
            if (resourceLoader.getResource(location).exists()) {
                logbackConfigs.add(location);
            } else {
                log.info("load-logback-config-not-found=" + location);
            }
        }
    }

    //生成并重新定义 logback
    private void configLogback() {
        try {
            LogBackConfigLoader.load(logbackConfigs, false, appName);

        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }


    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        configLogback();
    }
}
