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

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpSession;

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

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

/**
 * @author VHIT Security and Other Common Services (S&OCS)
 * @version 1.1.0.007
 */
public class ContextWriter {
	
	private static Logger logger = Logger.getLogger(ContextWriter.class);

	private CcowEnv ccowEnv;

	public ContextWriter(CcowEnv ccowEnv) {
		this.ccowEnv = ccowEnv;
	}

	public void writeContext() {
		LoginUserInfoVO userInfo = getLoginUserInfoVo();
		Map newContext = getNewContext(userInfo);
		if (newContext != null){
			CommonContextSession ctxSession = joinContext(ccowEnv, userInfo);
			if (ctxSession != null){				
				try {
					ctxSession.setContext(newContext);
					ccowEnv.setActiveContextSession(ctxSession);
				} catch (KaajeeException e) {
					if (logger.isEnabledFor(Level.ERROR)) {
						logger.debug("error writing context: " + e);
					}		
					ctxSession.stop();
				}
			} else {
				if (logger.isEnabledFor(Level.DEBUG)) {
					logger.debug("common context session is null: " + ctxSession);
				}	
				//ccowEnv.terminateContextSession();
			}
		} else {
			if (logger.isEnabledFor(Level.DEBUG)) {
				logger.debug("new user context is null: " + newContext);
			}
			//ccowEnv.terminateContextSession();
		}
	}

	private LoginUserInfoVO getLoginUserInfoVo() {
		HttpSession session = ccowEnv.getHttpSession();
		return (LoginUserInfoVO) session.getAttribute(LoginUserInfoVO.SESSION_KEY);
	}

	private Map getNewContext(LoginUserInfoVO userInfo) {
		Map newContext = null;  // return value
		
		String idAndDomain = getKernelCcowToken(userInfo);
		if (idAndDomain == null) {
			return newContext;  // null
		}		
		String [] array = idAndDomain.split("\\n");
		if (array.length < 2){
			return newContext;  // null
		}
		String tokenId = array[0];
		String domainAndInstitution = array[1]; // "domainName^institutionNumber"
				
		String vpid = userInfo.getUserVpid();
		String name = userInfo.getUserName01();
		String vistaName = name;
		
		newContext = new HashMap();
		newContext.put(CommonContextMap.VHA_CCOW_LOGON_NAME, vistaName);
		newContext.put(CommonContextMap.VHA_CCOW_LOGON_TOKEN, tokenId);
		newContext.put(CommonContextMap.VHA_CCOW_LOGON_DOMAIN, domainAndInstitution);
		newContext.put(CommonContextMap.VHA_CCOW_LOGON_VPID, vpid);
		newContext.put(CommonContextMap.VHA_CCOW_LOGON_NAME_GENERIC, name);
		
		if (logger.isEnabledFor(Level.DEBUG)) {
			logger.debug("new context :" 
					+ vistaName + "\n" 
					+ tokenId + "\n" 
					+ domainAndInstitution + "\n"
					+ vpid + "\n"
					+ name + "\n");;
		}
		
		return newContext;
	}
	
	private String getKernelCcowToken(LoginUserInfoVO userInfo) {
		String token = null;
		String institution = userInfo.getLoginStationNumber();
		String duz = userInfo.getUserDuz();
		String clientIP = ccowEnv.getClientIPAddr();
		token = VistALogon.getKernelCcowToken(institution, duz, clientIP);
		return token;
	}
	
	private CommonContextSession joinContext(CcowEnv ccowEnv, LoginUserInfoVO userInfo) {
		// join common context if any
		CommonContextSession ctxSession = null;
		String passcode = getPasscode(userInfo);  // must have a value to have writing privileges
		if (passcode != null && passcode.length() > 0){
			// we want to start a contextor with writing capabilities; so passcode must not be null
			ctxSession = ContextManager.joinWriteContext(passcode, ccowEnv);
		} else {
			if (logger.isEnabledFor(Level.DEBUG)) {
				logger.debug("failed to obtain the passcode");
			}
		}
	
		return ctxSession;
	}
	
    private String getPasscode(LoginUserInfoVO userInfo) {
		// TODO Auto-generated method stub
    	//return "kqdQ8siyn1_XwshtOYUJU6orRQVV_PWhKWK9TVbRGG3AnVlKoSHPTRbS-KP3MLAYq5wcmkKIDZUaLWELN0uiAbseTlqwK0ARhZEPqoJzyn9r319qvp_kWP1_dGEIQmnoB4pKsVrVqCMEXMNZdQ0KCp5QeX7nHqg1oQwxHRlH1MpMwnUBFTqAZgs_wfDwDgitY3sDyAM3fKnQtXQBSUaH2a5ZfFajnJxCERavwh3aWOgsHoKwyTmDSssHupUjnPy7";
    	String passCode = null;
    	String institution = userInfo.getLoginStationNumber();
		String duz = userInfo.getUserDuz();
    	passCode = VistALogon.getSecureCcowPasscode(institution, duz);
    	return passCode;
	}

}
