package edu.georgetown.blackboard.coursecombiner.b2.support;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.web.context.ConfigurableWebApplicationContext;

public class CourseCombinerApplicationContextInitializer implements ApplicationContextInitializer<ConfigurableWebApplicationContext> {
    
    public static final String EXTERNAL_PROPERTIES_FILE = "/nas/bbrepo/bbsnapshot/course-combiner-engine-home/config/course-combiner-b2.properties";
    
    private Logger log = LoggerFactory.getLogger(CourseCombinerApplicationContextInitializer.class);

    @Override
    public void initialize(ConfigurableWebApplicationContext applicationContext) {
        PropertiesPropertySource propertySource = new PropertiesPropertySource("CourseCombinerB2PropertySource", loadProperties());
        applicationContext.getEnvironment().getPropertySources().addFirst(propertySource);
    }
    
    private Properties loadProperties() {
        Properties props = new Properties();
        
        log.debug("Attempting to load external application properties from: {}", EXTERNAL_PROPERTIES_FILE);
        
        try (FileInputStream fis = new FileInputStream(EXTERNAL_PROPERTIES_FILE)) {
            props.load(fis);
            log.debug("Successfully loaded external application properties from: {}", EXTERNAL_PROPERTIES_FILE);
        } catch (IOException e) {
            throw new RuntimeException("Error loading external properties file: " + EXTERNAL_PROPERTIES_FILE, e);
        }
        
        return props;
    }

}
