package gov.va.med.mpn.auth.web;

import java.net.URI;
import java.util.ResourceBundle;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import javax.ws.rs.core.UriBuilder;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.client.OAuth2RestTemplate;
import org.springframework.web.context.support.SpringBeanAutowiringSupport;

/**
 * This class is responsible for disposing of resources when a user's 
 * session expires. This includes issuing a request to the Health Adapter
 * service to delete the user's authorization token.
 * 
 * @author <a href="mailto:chris.barthauer@hp.com">Chris Barthauer</a>
 *
 */
public class CustomOAuthSessionListener implements HttpSessionListener {
	private final Logger logger = LoggerFactory
			.getLogger(CustomOAuthSessionListener.class);
	
	private ResourceBundle props;
	
	/** The trusted client rest template. */
	@Autowired
	private OAuth2RestTemplate trustedClientRestTemplate;
	
	public CustomOAuthSessionListener() {
		logger.debug("Entered constructor.");
		
		//Load settings from authorization.properties file.
		props = ResourceBundle.getBundle("authorization");
		logger.debug("ha.deletetoken.url:" + props.getString("ha.deletetoken.url"));
		
		//Resolve Spring @Autowired annotations; inject dependencies.
		SpringBeanAutowiringSupport.processInjectionBasedOnCurrentContext(this);
	}
	
	@Override
	public void sessionCreated(HttpSessionEvent event) {
		logger.debug("Creating session.");		
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent event) {
		logger.debug("Destroying session.");
		URI deleteTokenURL = UriBuilder.fromPath(props.getString("ha.deletetoken.url")).build();
		logger.debug("Deleting Health Adapter authorization token using URL: {}", deleteTokenURL.toString());
		trustedClientRestTemplate.delete(deleteTokenURL);
	}
}
