package gov.va.vss.web;

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

import org.apache.commons.lang.exception.ExceptionUtils;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

import gov.va.shared.util.SecurityUtil;
import gov.va.vss.model.volunteer.Volunteer;
import gov.va.vss.web.interceptor.AbstractReferenceDataInterceptor;

public abstract class AbstractKioskController extends AbstractCommonAppController {

	public Volunteer getCurrentUser() {
		return SecurityUtil.getCurrentUserAs(Volunteer.class);
	}
	
	@ExceptionHandler(Throwable.class)
	public ModelAndView processError(Throwable ex, HttpServletRequest request, HttpServletResponse response) {
		if (isAjax(request)) {
			/*
			 * Necessary to trigger the jQuery error() handler as opposed to the
			 * success() handler - CPB
			 */
			response.setStatus(HttpStatus.BAD_REQUEST.value());
			return ajaxRequestHandler.getExceptionModelAndView(ex, request);
		} else {
			ModelAndView mv = new ModelAndView("error", "exceptionStackTrace", ExceptionUtils.getFullStackTrace(ex));
			AbstractReferenceDataInterceptor.populateBasicGlobalReferenceData(mv.getModel(), velocityService, env);
			return mv;
		}
	}
	
	@InitBinder
	public final void initBinder(WebDataBinder binder) {
		binder.setDisallowedFields(getDisallowedBinderFields());
	}

	protected String[] getDisallowedBinderFields() {
		return new String[] {};
	}

	public Long getKioskId(HttpServletRequest request) {
		Cookie kioskIdCookie = WebUtils.getCookie(request, "vssKioskId");
		Long kioskId = kioskIdCookie == null ? null : new Long(kioskIdCookie.getValue());
		return kioskId;
	}

}
