package gov.va.med.mpn.xpl.processor;

import gov.va.med.mpn.constants.SessionAttributeNames;

import java.util.Date;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.pipeline.api.PipelineContext;
import org.orbeon.oxf.processor.ProcessorInputOutputInfo;
import org.orbeon.oxf.processor.SimpleProcessor;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

public class SessionLogoutProcessor extends SimpleProcessor {	
	private final Logger logger = LoggerFactory
			.getLogger(SessionLogoutProcessor.class);
	
	public SessionLogoutProcessor() {
		addOutputInfo(new ProcessorInputOutputInfo("data"));
	}
	
	public void generateData(
			PipelineContext context, 
			ContentHandler handler) throws SAXException {
		logger.debug("Entered generateData(...).");
		
		ExternalContext externalContext = 
				(ExternalContext) context.getAttribute(PipelineContext.EXTERNAL_CONTEXT);
		ExternalContext.Session session = externalContext.getRequest().getSession(false);
		Map<String, Object> sessionAttributes = session.getAttributesMap(session.APPLICATION_SCOPE);
		Date lastUserActiveDate = (Date) sessionAttributes.get(SessionAttributeNames.LAST_USER_ACTIVE_DATE);
		logger.debug("lastUserActiveDate: " + lastUserActiveDate);
		
		//TODO: Refactor.
		long lastUserActiveMilliSecs = lastUserActiveDate.getTime();
		long currentMilliSecs = (new Date()).getTime();
		long inactiveMilliSecs = currentMilliSecs - lastUserActiveMilliSecs;
		double inactiveMinutes = inactiveMilliSecs / 1000.0 / 60.0;
		logger.debug("inactiveDurationMinutes: " + inactiveMinutes);
		
		double maxInactiveMinutes = ((double) session.getMaxInactiveInterval()) / 60.0;
		logger.debug("maxInactiveMinutes: " + maxInactiveMinutes);
		
		boolean shouldLogout = inactiveMinutes >= maxInactiveMinutes;		
		logger.debug("shouldLogout: " + shouldLogout);
		
		Document outputDoc = createOutputDocument(shouldLogout);
		MpnProcessorUtils.writeOutput(outputDoc, handler);
	}
	
	private Document createOutputDocument(boolean shouldLogout) {
		Document result = DocumentHelper.createDocument();
		Element root = result.addElement("SessionTimerResponse");
		root.addElement("ShouldLogout")
			.addText(Boolean.toString(shouldLogout));
		return result;
	}
}