package com.friday.dynamic.core;

import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Enumeration;
import java.util.Properties;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.stereotype.Component;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
public class EnvironmentLoader {
	
	@Value("${spring.profiles.active}")
	private String env;
	
	@Autowired
	private ConfigurableApplicationContext applicationContext;
	
	public void load(Path jarPath) throws Exception {
		ConfigurableEnvironment environment = applicationContext.getEnvironment();
		final JarFile jarFile = new JarFile(jarPath.toFile());
		Enumeration<JarEntry> entries = jarFile.entries();
		while(entries.hasMoreElements()) {
			JarEntry entry = entries.nextElement();
            String entryName = entry.getName();
            //读取配置文件
            if (!entry.isDirectory() && entryName.endsWith(env+".properties")) {
            	//加载resource
            	Properties properties = new Properties();
				Reader reader = new InputStreamReader(jarFile.getInputStream(entry), StandardCharsets.UTF_8);
				properties.load(reader);
    			//去除已有的配置，防止冲突
    			properties.stringPropertyNames().removeIf(environment::containsProperty);
    			if(!properties.isEmpty()) {
    				//加载配置
    				environment.getPropertySources().addLast(new PropertiesPropertySource(entry.getName(), properties));
    			}
            }
		}
	}
}
