package gov.va.med.authentication.kernel.ccow;

import gov.va.med.authentication.kernel.LoginUserInfoVO;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.log4j.Level;

import com.sentillion.sdkweb.webcontextor.ContextItemCollection;

/**
 * @author VHIT Security and Other Common Services (S&OCS)
 * @version 1.1.0.007
 */
public class ContextParticipant {
	
	private static Logger logger = Logger.getLogger(ContextParticipant.class);
	private static final String ACCEPTED = "ContextChangesAccepted";
//	private static final String CANCELED = "ContextChangesCanceled";
//	private static final String PENDING = "ContextChangesPending";
//	private static final String PING = "Ping";
	
	private ContextChangesMessage msg;

	public ContextParticipant(ContextChangesMessage msg) {
		this.msg = msg;
	}

	public void respond() {
		
		CcowEnv ccowEnv = msg.getCcowEnv();
		
		if (ccowEnv == null) { // ignore this message
			if (logger.isEnabledFor(Level.DEBUG)) {
				logger.debug("in contextParticipant respond: CcowEnv is null");
			}
			return;
		}
		boolean acceptChange = true;
		if (msg.getMethodValue().equalsIgnoreCase(ACCEPTED)) {
			acceptChange = handleChange();
		}
		// Always return decision=accept for all methods called
		HttpServletResponse res = msg.getResponse();
		String contents = "decision=accept";
		res.setContentType("application/x-www-form-urlencoded");
		res.setContentLength(contents.length());
		PrintWriter out;
		try {
			out = res.getWriter();
			out.write(contents);
		} catch (IOException e) {
			if (logger.isEnabledFor(Level.ERROR)) {
				logger.debug("error in writing response from the context participant");
			}
		}		
	}

	private  boolean handleChange() {
		boolean acceptChange = true;  // return value
		if (userChanged()) {
			logoff();
		}
		return acceptChange;  // always return true for now (user Context changes)
	}

	private  boolean userChanged() {
		boolean userChanged = false;  // return value
		String currentUser = null;
		String newUser = null;
		
		CcowEnv ccowEnv = msg.getCcowEnv();
		CommonContextSession ctxSession = ccowEnv.getActiveContextSession();
		if (ctxSession == null) {
			userChanged = true;
		} else { // there is a ccow session active
			ContextItemCollection newItemCollection = ctxSession.getCurrentContext();
			CommonContextMap newContext = new CommonContextMap(newItemCollection);
			newUser = newContext.getContextItem(CommonContextMap.VHA_CCOW_LOGON_NAME);
			LoginUserInfoVO userInfo = ccowEnv.getLoginUserInfo();
			if (userInfo != null) {
				currentUser = userInfo.getUserName01();
			}

			if (logger.isEnabledFor(Level.DEBUG)) {
				logger.debug("\ncurrent user is : " + currentUser);
				logger.debug("\nnew user is : " + newUser);
			}

			if (newUser != null && currentUser != null){
				userChanged = !newUser.equals(currentUser);
			} else {
				userChanged = true;
			}
		}
		return userChanged;
	}
	

	private void logoff() {
		
		if (logger.isEnabledFor(Level.DEBUG)) {
			logger.debug("\ncurrent user is being logged off");			
		}
		CcowEnv ccowEnv = msg.getCcowEnv();
		ccowEnv.getHttpSession().invalidate();

	}
}
