package org.jboss.aerogear.unifiedpush.service;

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

import javax.annotation.PostConstruct;
import javax.ejb.Singleton;
import javax.ejb.Startup;

import org.jboss.aerogear.unifiedpush.utils.AeroGearLogger;

@Singleton
@Startup
public class Configuration {
	
    private final AeroGearLogger logger = AeroGearLogger.getInstance(Configuration.class);

	// todo: rename
	private static final String PROPERTIES_FILE_KEY = "aerogear.config";
	
	private Properties properties;
	
	@PostConstruct
	public void loadProperties() {
		final String propertiesFilePath = System.getProperty(PROPERTIES_FILE_KEY);
		properties = new Properties();
		
		if (propertiesFilePath != null) {
			File propertiesFile = new File(propertiesFilePath);
			try (InputStream inp = new FileInputStream(propertiesFile)) {
				properties.load(inp);
			} catch (IOException e) {
			    logger.severe("Cannot load configuration", e);
			} 
		}
	}
	
	public String getProperty(String key) {
		return properties.getProperty(key);
	}
	
	public Properties getProperties() {
		return new PropertiesView(properties);
	}
	
	@SuppressWarnings("serial")
	private class PropertiesView extends Properties {
		private final Properties properties;
		
		public PropertiesView(Properties properties) {
			this.properties = properties;
		}
		
		public String getProperty(String key) {
			return properties.getProperty(key);
		}
	}
}

@@ -87,32 +87,70 @@
 ileInputStream;%0A
+import java.io.FileNotFoundException;%0A
 import java.io.I
@@ -521,25 +521,8 @@
 );%0A%0A
-%09// todo: rename%0A
 %09pri
@@ -886,27 +886,39 @@
 try 
-(InputStream inp = 
+%7B%0A%09%09%09%09loadPropertiesFromStream(
 new 
@@ -953,35 +953,8 @@
 le))
- %7B%0A%09%09%09%09properties.load(inp)
 ;%0A%09%09
@@ -963,18 +963,28 @@
  catch (
-IO
+FileNotFound
 Exceptio
@@ -993,20 +993,17 @@
 e) %7B%0A%09%09%09
-    
+%09
 logger.s
@@ -1013,45 +1013,94 @@
 re(%22
-C
+c
 annot 
-load configuration%22, e);%0A%09%09%09%7D 
+open file %22 + propertiesFilePath);%0A%09%09%09%7D %0A%09%09%7D else %7B%0A%09%09%09loadDefaultProperties();
 %0A%09%09%7D
@@ -1272,16 +1272,465 @@
 );%0A%09%7D%0A%09%0A
+%09private void loadDefaultProperties() %7B%0A%09%09InputStream inp = getClass().getClassLoader().getResourceAsStream(%22default.properties%22);%0A%09%09if (inp == null) %7B%0A%09%09%09logger.warning(%22default properties not found%22);%0A%09%09%7D%0A%09%09loadPropertiesFromStream(inp);%0A%09%7D%0A%09%0A%09private void loadPropertiesFromStream(InputStream inp) %7B%0A%09%09try (InputStream in = inp) %7B%0A%09%09%09properties.load(in);%0A%09%09%7D catch (IOException e) %7B%0A%09%09    logger.severe(%22Cannot load configuration%22, e);%0A%09%09%7D %0A%09%7D%0A%09%0A
 %09@Suppre

Support a default configuration