package gov.va.med.edp.web.controller;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;

/**
 * TODO: document BigBoardClientVersionSynchronizationController
 */
public class BigBoardClientVersionSynchronizationController extends ClientVersionSynchronizationController {


	private String errorMsg;

    private static Logger logger = Logger.getLogger(BigBoardClientVersionSynchronizationController.class);

	
    public void afterPropertiesSet() throws Exception {
    	setRequireSession(false);
        super.afterPropertiesSet();
        Assert.notNull(serverPackageVersionDao, "serverPackageVersionDao must not be null");
    	Assert.notNull(getSiteCodeDao(), "siteCodeDao is required");
    	Assert.notNull(getTrackingDao(), "trackingDao is required");
    	
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	//First attempt is to get the machineName from HTTP Header:EdisClientMachineName as decided 
    	// this HTTP header is appended by the load balancer and the value of this header (the machine name)
    	//is parsed by the load balancer.
    	String machineName = parseCNFromHttpHeaders(request.getHeader(MACHINE_NAME_HEADER));    	

    	if (StringUtils.hasText(machineName)){
    		debug("Machine name obtained from HTTP Header:" + MACHINE_NAME_HEADER + " was: " + machineName);
    	} else {
    		debug("No Machine name was found in HTTP Header:" + MACHINE_NAME_HEADER );
    		machineName = getMachineNameFromUserPrincipalOrSessionOrRequest(request);
    	}
    	//set the machine name in an existing session for refreshes/restored sessions
		HttpSession session = request.getSession(false);
		if (session != null){
		session.setAttribute(MACHINE_NAME_PARAM, machineName);
		} else {
    		return createErrorModelAndView("Invalid Session was detected. Please try re-launching the EDIS Big Board");
		}
    	
    	String siteCode = getSiteCodeDao().getSiteCode(machineName);
		debug("Site Code Obtained for Machine: " + machineName + " was: " + siteCode);

    	if (!StringUtils.hasText(siteCode)){
    		errorMsg = "A matching site code for the machine: " + machineName + " was not found in the EDP.SiteMapper table.\n" +
    						"Please contact the EDIS national help desk with this message for remedy.";
    		return createErrorModelAndView(errorMsg);
    	}    	
		
		String serverPackageVersion = (String) request.getSession().getAttribute(SessionConstants.SERVER_PACKAGE_VERSION_KEY);
    	if (serverPackageVersion == null) {
        	serverPackageVersion = serverPackageVersionDao.getServerPackageVersion(siteCode);
            request.getSession().setAttribute(SessionConstants.SERVER_PACKAGE_VERSION_KEY, serverPackageVersion);
        }
		debug("serverPackageVersion is: " + serverPackageVersion);

    	if (isBoardNameAvailableForMachine(siteCode, machineName, request)) return super.handleRequestInternal(request, response);
        
        return createErrorModelAndView(errorMsg);
    }

	private boolean isBoardNameAvailableForMachine(String siteCode, String machineName, HttpServletRequest request) {
		String result = getTrackingDao().executeCommand(siteCode, "0", buildParameterMap(request,machineName));
    	if (result.startsWith("<error>")){
    		int start = result.indexOf("<error>");
    		int end = result.indexOf("</error>");
    		errorMsg = result.substring(start + 7, end);
    		debug("isBoardNameAvailableForMachine: false");
    		return false;
    	} 
    	debug("isBoardNameAvailableForMachine: true");
    	return true;
	}

    private void debug(String s) {
    	if (logger.isDebugEnabled()){
    		logger.debug(s);
    	}
	}

}
