package cz.muni.fi.lasaris.sbms;


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

import org.apache.log4j.Logger;
import org.glassfish.jersey.server.ResourceConfig;
import org.glassfish.jersey.server.filter.RolesAllowedDynamicFeature;

import cz.muni.fi.lasaris.sbms.api.auth.AuthenticationFilter;
import cz.muni.fi.lasaris.sbms.model.TdbConnector;

public class SBMSApplication extends ResourceConfig {
	final static Logger logger = Logger.getLogger(SBMSApplication.class);
	private Properties prop;
	
	private static SBMSApplication instance;

	public static SBMSApplication getInstance() {
		if(instance == null) {
			instance = new SBMSApplication();
		}
		return instance;
	}
	
	protected SBMSApplication() {
		super();
		// http://crunchify.com/java-properties-file-how-to-read-config-properties-values-in-java/
		this.prop = new Properties();
		try {
			String propFileName = "sbms.properties";

			InputStream inputStream = TdbConnector.class.getClassLoader().getResourceAsStream(propFileName);

			if (inputStream != null) {
				this.prop.load(inputStream);
			} else {
				logger.error("property file '" + propFileName + "' not found in the classpath");
			}
		} catch (Exception ex) {
			logger.error(ex);
			logger.error("Error occured when reading properties");
		}
		
		packages("cz.muni.fi.lasaris.sbms.api");
		register(RolesAllowedDynamicFeature.class);
		if (prop.getProperty("api.customAuth.enable") != null && Boolean.parseBoolean(prop.getProperty("api.customAuth.enable"))) {
			register(AuthenticationFilter.class);
		}
		
		//TdbConnector.setPaths("F:\\sbms\\sbimtdb");
        TdbConnector.setPaths((prop.getProperty("tdb.path") != null) ? prop.getProperty("tdb.path") : "./sbmstdb");
		//ModelUpdater.cleanup();
        TdbConnector.open();
	}
	
	public Properties getSBMSProperties() {
		
		return prop;
	}
	
	public String getURI() {
		return prop.getProperty("api.uri");
	}
	
	public void close() {
		TdbConnector.close();
	}

}
