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

import java.util.Enumeration;
import java.util.Iterator;

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.mvc.AbstractController;

/**
 * TODO: document PackageClientVersionSynchronizationController
 */
public class TestController extends AbstractController implements InitializingBean {

    public static final String EDIS_MACHINE_NAME_HEADER = "EdisClientMachineName";
    
    private String viewName;
    private static Logger logger = Logger.getLogger(TestController.class);

    public TestController() {
        setRequireSession(true);
    }

    public void afterPropertiesSet() throws Exception {
        Assert.notNull(viewName, "viewName must not be null");
    }

    protected ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response) throws Exception {
    	if (logger.isDebugEnabled()){
    		logger.debug("Inside handleRequestInternal() method. The view name is:" + getViewName());
    		logger.debug("The value for the HTTP Header '" + EDIS_MACHINE_NAME_HEADER + "' is: " + getClientMachineName(request));
    	}
    		
        ModelAndView mav = new ModelAndView(getViewName());
        mav.addObject(EDIS_MACHINE_NAME_HEADER, getClientMachineName(request));
        mav.addObject("HttpHeaders", getAllHttpHeaders(request));
        return mav;    
    }


    private Object getAllHttpHeaders(HttpServletRequest request) {
		String headers = "";
		Enumeration headersEnum = request.getHeaderNames();
		while (headersEnum.hasMoreElements()) {
			String headerName = (String) headersEnum.nextElement();
			headers = headers + headerName + "=" + request.getHeader(headerName) + "<br/>";
		}
		return headers;
	}

	private String getClientMachineName(HttpServletRequest request) {
		return parseMachineName(request.getHeader(EDIS_MACHINE_NAME_HEADER));
	}

    
    private String parseMachineName(String machineName){
    	if (StringUtils.hasText(machineName) && machineName.startsWith("CN=")){
    		String name = machineName.substring(3);
    		return name;
    	}
    	return machineName;
    }
    
	public String getViewName() {
        return viewName;
    }

    public void setViewName(String viewName) {
        this.viewName = viewName;
    }


}
