package gov.va.vss.web.interceptor;

import java.util.Map;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import gov.va.vss.web.conversion.interceptor.AbstractInterceptor;

public abstract class AbstractModelDrivenPostInterceptor extends AbstractInterceptor {
	private static final Logger log = LoggerFactory.getLogger(AbstractReferenceDataInterceptor.class);

	@Override
	public final void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		if (isAjax(request)) {
			log.debug("Request was an AJAX request, skipping interceptor...");
			return;
		}

		if (modelAndView == null) {
			log.debug("No modelAndView returned, the controller must have dealt with the response manually.");
			return;
		}

		Map<String, Object> model = modelAndView.getModel();
		if (model == null) {
			log.error("No model in the ModelAndView, that is unexpected. Returning without executing interceptor...");
			return;
		}

		if (modelAndView.getView() instanceof RedirectView
				|| (modelAndView.isReference() && modelAndView.getViewName().startsWith("redirect:"))) {
			log.debug("View is null or a redirect, no need to populate reference data");
			return;
		}

		postHandleWithValidModel(request, response, handler, model);
	}

	protected abstract void postHandleWithValidModel(HttpServletRequest request, HttpServletResponse response, Object handler,
			Map<String, Object> model) throws Exception;

}
