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


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

import javax.ws.rs.ApplicationPath;

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.semantics.logic.TdbConnector;

@ApplicationPath("semantics/")
public class Application extends ResourceConfig {
	final static Logger logger = Logger.getLogger(Application.class);
	private Properties prop;
	
	public Application() {
		super();
		setApplicationName("Semantic BMS Semantic API");
		// http://crunchify.com/java-properties-file-how-to-read-config-properties-values-in-java/
		this.prop = new Properties();
		try {
			String propFileName = "semantics.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.semantics.api");
		register(RolesAllowedDynamicFeature.class);
		registerInstances(new AuthenticationFilter("semantics", prop));
		// TODO: data-level auth (semantic API)
		
		TdbConnector.init(prop);
        //ModelUpdater.cleanup();
        TdbConnector.open();
	}
	
	public Properties getSBMSProperties() {
		
		return prop;
	}
	
	public static void close() {
		TdbConnector.close();
	}
	
	public void finalize() {
		logger.debug("Closing TDB...");
		TdbConnector.close();
		logger.debug("TDB closed.");
	}

}
