package cz.muni.fi.lasaris.sbms.data;

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

import javax.servlet.ServletContext;
import javax.ws.rs.ApplicationPath;
import javax.ws.rs.core.Context;

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

import cz.muni.fi.lasaris.sbms.auth.AuthenticationFilter;
import cz.muni.fi.lasaris.sbms.data.logic.ProviderManager;

@ApplicationPath("data/")
public class Application extends ResourceConfig {
	final static Logger logger = Logger.getLogger(Application.class);
	private Properties prop;
	@Context ServletContext context;
	
	public Application() {
		super();
		setApplicationName("Semantic BMS Data Access API");
		
		// http://crunchify.com/java-properties-file-how-to-read-config-properties-values-in-java/
		this.prop = new Properties();
		try {
			String propFileName = "data.properties";

			InputStream inputStream = Application.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.data.api");
		
		register(RolesAllowedDynamicFeature.class);
		registerInstances(new AuthenticationFilter("data", prop));
		// TODO: data-level auth (data API)
		
		try {
			ProviderManager.init(prop);
		} catch(Throwable e) {
			logger.error("Initialization error", e);
		}
	}
	
	public Properties getSBMSProperties() {
		return prop;
	}
	
	public static void close() {
		logger.debug("Closing connectors...");
		ProviderManager.close();
		logger.debug("Connectors closed.");
	}
	
	public void finalize() {
		close();
	}

}
