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

import gov.va.med.edp.vo.BigBoardDebugInfoVO;
import gov.va.med.edp.web.view.XmlView;

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

import org.apache.log4j.Logger;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.WebContentGenerator;

public class BigDisplayBoardController extends SiteCodeController implements InitializingBean {

    private static final String MACHINE_NAME_PARAM = SiteCodeController.MACHINE_NAME_PARAM;
    public static final String MACHINE_NAME_HEADER = SiteCodeController.MACHINE_NAME_HEADER;

    protected static final String XML_VIEW = "xmlView";
    
    private static Logger log = Logger.getLogger(BigDisplayBoardController.class);

    public BigDisplayBoardController() {
        setRequireSession(false);
        setSupportedMethods(new String[]{WebContentGenerator.METHOD_POST, WebContentGenerator.METHOD_GET});
    }

    public void afterPropertiesSet() throws Exception {
    	Assert.notNull(getSiteCodeDao(), "siteCodeDao is required");
    	Assert.notNull(getTrackingDao(), "trackingDao is required");
    	Assert.notNull(getServerPackageVersionDao(), "ServerPackageVersionDao is required");
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String result = "";
    	//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)){
			clearRequestAndSession(request);
    	} else {
    		machineName = getMachineNameFromUserPrincipalOrSessionOrRequest(request);
    	}
    	debug("Machine name obtained from certificate/HTTP Header/request/session:" + machineName);
    	String siteCode = getSiteCodeDao().getSiteCode(machineName);
    	
    	if (!StringUtils.hasText(siteCode)){
    		String errorMsg = "No site code was found for the machine name: " + machineName;
    		return createErrorModelAndView(errorMsg);
    	}    	

    	result = getTrackingDao().executeCommand(siteCode, "0", buildParameterMap(request,machineName));
    	if (isInitCommand(request))
    	result = appendSiteAndVistaLinkConnectionInfo(result, request, siteCode, machineName);    	
    	return createModelAndView(result, siteCode, machineName);
    }


	private void clearRequestAndSession(HttpServletRequest request) {
		request.getSession().setAttribute(MACHINE_NAME_PARAM, null);
		request.setAttribute(MACHINE_NAME_PARAM, null);
	}

	private boolean isInitCommand(HttpServletRequest request) {
		if (request.getParameter("command").equals("initDisplayBoard")) return true;
		return false;
	}	

    protected ModelAndView createModelAndView(String result, String siteCode, String machineName) {
    	return new ModelAndView(XML_VIEW, XmlView.XML_FRAGMENT, result);
    }

    private String appendSiteAndVistaLinkConnectionInfo(String result,HttpServletRequest request, String siteCode, String machineName) {
    	BigBoardDebugInfoVO vistalinkInfo = serverPackageVersionDao.getVistaLinkConnectionInfo(siteCode);
    	vistalinkInfo.setSiteId(siteCode);
    	vistalinkInfo.setMachineName(machineName);
    	result = result.concat(vistalinkInfo.toString());
    	return result;
    }

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


}
