package it.mice.voila.runtime.springmvc.resolver;

import java.net.SocketException;

import it.mice.voila.runtime.exception.BusinessException;
import it.mice.voila.runtime.springmvc.controller.PopupController;
import it.mice.voila.runtime.springmvc.flashmap.FlashMap;
import it.mice.voila.runtime.springmvc.util.SpringMvcUtil;
import it.mice.voila.runtime.util.UserMessages;

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

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver;

public class LastPathExceptionResolver extends AbstractHandlerExceptionResolver {
	private static final Log log = LogFactory.getLog(LastPathExceptionResolver.class);

	@Override
	protected ModelAndView doResolveException(HttpServletRequest request,
			HttpServletResponse response, Object handler, Exception ex) {

		if (ex instanceof BusinessException) {
			UserMessages userMessages = ((BusinessException)ex).getUserMessages();
			FlashMap.getMessages().addUserMessages(userMessages);
		} else {
			if (ex instanceof SocketException) {
				log.error("Generic error: " + ex.getMessage());
			} else {
				log.error("Generic error:", ex);
			}
			//FlashMap.getMessages().addErrorMessage("error.generic", ex.getLocalizedMessage());
			FlashMap.getMessages().addErrorMessage("error.generic", "Operazione interdetta, contattare l'assistenza tecnica.");
		}
		if (handler instanceof PopupController) {
			//FIXME - define a generic error page to forward to in order to avoid rendering of a management page in a popup.
			return new ModelAndView((String)request.getSession().getAttribute(SpringMvcUtil.LAST_VIEW_NAME));
		}
		SpringMvcUtil.doLastPathRedirect(request, response, request.getRequestURI(), 0, request.getRequestURI());
		return new ModelAndView();
	}
}
