package com.eactive.eai.env;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import javax.annotation.PostConstruct;
import javax.servlet.ServletContext;

import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.ServletContextAware;

@Configuration
public class SystemPropConfig implements ServletContextAware {

	private ServletContext servletContext;
	
	private final String SYSTEM_PROP_FILE_PATH = "/WEB-INF/properties/env.system.properties";
	
	@Override
	public void setServletContext(ServletContext servletContext) {
		this.servletContext = servletContext;
	}
	
	@PostConstruct
	public void loadlPropertiesToSystemProp() {
		// System.out.println("loadPropertiesToSystemProp: "+SYSTEM_PROP_FILE_PATH);
		Properties sysProp = new Properties();
		try(InputStream is = servletContext.getResourceAsStream(SYSTEM_PROP_FILE_PATH)){
			sysProp.load(is);
			sysProp.forEach((key, value) -> {
				if (StringUtils.isBlank(System.getProperty((String) key))) {
					System.setProperty((String) key, (String) value);
					// System.out.println("Set system prop: "+key+"="+value);
				}
			});
		} catch (Throwable th) {
			System.err.println(SYSTEM_PROP_FILE_PATH+" load failed. - "+ th.getMessage());
		}
	}
}
