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

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

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.orbeon.oxf.webapp.WebAppContext;
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 SessionPropertiesProcessor extends SimpleProcessor {	
	private final Logger logger = LoggerFactory
			.getLogger(SessionPropertiesProcessor.class);
	
	public SessionPropertiesProcessor() {
		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);
		WebAppContext waContext = externalContext.getWebAppContext();
		Map<String, String> paramMap = waContext.getInitParametersMap();
		
		String warningTimerUrl = paramMap.get(ContextParameterNames.WARNING_TIMER_URL);
		String warningTimerDelay = paramMap.get(ContextParameterNames.WARNING_TIMER_DELAY);
		String logoutTimerUrl = paramMap.get(ContextParameterNames.LOGOUT_TIMER_URL);
		String logoutTimerDelay = paramMap.get(ContextParameterNames.LOGOUT_TIMER_DELAY);	
		String logoutUrl = paramMap.get(ContextParameterNames.LOGOUT_URL);
		
		Document outputDoc = createOutputDocument(
				warningTimerUrl,
				warningTimerDelay,
				logoutTimerUrl,
				logoutTimerDelay,
				logoutUrl);	
		MpnProcessorUtils.writeOutput(outputDoc, handler);
	}
	
	private Document createOutputDocument(
			String warningTimerUrl,
			String warningTimerDelay,
			String logoutTimerUrl,
			String logoutTimerDelay,
			String logoutUrl) {
		Document result = DocumentHelper.createDocument();
		Element root = result.addElement("SessionTimerResponse");
		
		Element warningTimer = root.addElement("WarningTimer");
		warningTimer.addElement("Url")
			.addText(warningTimerUrl);
		warningTimer.addElement("Delay")
			.addText(warningTimerDelay);
		
		Element logoutTimer = root.addElement("LogoutTimer");
		logoutTimer.addElement("Url")
			.addText(logoutTimerUrl);
		logoutTimer.addElement("Delay")
			.addText(logoutTimerDelay);
		
		root.addElement("LogoutUrl")
			.addText(logoutUrl);
		return result;
	}
}