package cc.smtweb.framework.core.mvc.config;

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.env.EnvironmentPostProcessor;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.io.FileSystemResource;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 〈读取外部配置文件〉
 *
 * @author kevin
 * @since 1.0.0
 */
public class SettingsEnvironmentPostProcessor implements EnvironmentPostProcessor {

    @Override
    public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment,
                                       SpringApplication springApplication) {
        List<File> files = this.getProperties();
        for (File file : files) {
            if (file.exists()) {
                YamlPropertiesFactoryBean yaml = new YamlPropertiesFactoryBean();
                FileSystemResource resource = new FileSystemResource(file);
                yaml.setResources(resource);
                if (yaml.getObject() != null) {
                    configurableEnvironment.getPropertySources()
                            .addLast(new PropertiesPropertySource(file.getName(), yaml.getObject()));
                }
            }
        }
    }

    /**
     * <>获取所有资源配置文件</>
     */
    private List<File> getProperties() {
        List<File> result = new ArrayList<>();
        String tomcatConf = System.getProperty("catalina.base") + File.separator + "conf" + File.separator;
        File[] listFiles = new File(tomcatConf).listFiles();
        if (listFiles != null && listFiles.length > 0) {
            for (File lf : listFiles) {
                if (lf.isFile()) {
                    if (lf.getName().endsWith(".yaml")) {
                        result.add(lf);
                    }
                }
            }
        }
        return result;
    }

}