package com.ejie.m62fb.utils.exception;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import com.ejie.m62fb.utils.constants.IberErrorsMsgConstants;
import com.ejie.m62fb.utils.error.CannotServeHtmlException;
import com.ejie.m62fb.utils.error.UFException;

/**
 * 
XXXX
 * 
 */
public class IberExceptionHandler {

	@Autowired
	private ReloadableResourceBundleMessageSource messageErrorsSource;
	private static Logger logger =  LoggerFactory.getLogger(IberExceptionHandler.class);
	@ExceptionHandler(value = DuplicateKeyException.class)
	@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE)
	public void handleDuplicateKey(DuplicateKeyException ex,
			HttpServletResponse response, Locale locale) {
		try {
			String msg = IberErrorsMsgConstants.DUPLICATE_KEY_MSG;
			// if (ex.getMessage() != null && !"".equals(ex.getMessage())) {
			// msg = ex.getMessage();
			// }
			response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
					messageErrorsSource.getMessage(msg, null, locale));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 
	 * @param rnf
	 *            UFException
	 * @param request
	 *            HttpServletRequest
	 * @param response
	 *            HttpServletResponse
	 * @param locale
	 *            Locale
	 */
	@ExceptionHandler(value = UFException.class)
	@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE)
	public void handleUFException(UFException rnf, HttpServletRequest request,
			HttpServletResponse response, Locale locale) {
		try {
			response.setHeader("returnFeedbackId",
					request.getHeader("returnFeedbackId"));
			List<String> params = null;

			/* Si tiene parametros buscamos su literal */
			if (rnf.getUFParams() != null && rnf.getUFParams().size() > 0) {
				params = new ArrayList<String>();
				for (int i = 0; i < rnf.getUFParams().size(); i++) {
					params.add(messageErrorsSource.getMessage((String) rnf
							.getUFParams().get(i), null, locale));
				}
			}
			response.getOutputStream().print(messageErrorsSource.getMessage(rnf.getMessage(),
					params != null ? params.toArray() : null, locale));
			response.setStatus(HttpServletResponse.SC_NOT_ACCEPTABLE);
//			response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
//					messageErrorsSource.getMessage(rnf.getMessage(),
//							params != null ? params.toArray() : null, locale));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * Tratamiento de excepciones HTML.
	 * 
	 * @param htmlEx
	 *            CannotServeHtmlException
	 * @param response
	 *            HttpServletResponse
	 * @return ModelAndView para el error.
	 */
	@ExceptionHandler(value = CannotServeHtmlException.class)
	@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE)
	public ModelAndView handleHtmlException(CannotServeHtmlException htmlEx,
			HttpServletResponse response) {
		// Non-AJAX request
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.setViewName("error");
		modelAndView.addObject("exception_name", htmlEx.getClass().getName());
		modelAndView.addObject("exception_message", htmlEx.getMessage());
		StringBuilder sbTrace = new StringBuilder();
		for (StackTraceElement trace : htmlEx.getStackTrace()) {
			sbTrace.append(trace.toString()).append("</br>");
		}
		modelAndView.addObject("exception_trace", sbTrace);
		return modelAndView;
	}

	/**
	 * Resto de excepciones que se pueden lanzar.
	 * 
	 * @param ex
	 *            Exception
	 * @param response
	 *            HttpServletResponse
	 */
	@ExceptionHandler(value = Exception.class)
	@ResponseStatus(value = HttpStatus.NOT_ACCEPTABLE)
	public void handleException(Exception ex, HttpServletResponse response,
			Locale locale) {
		try {
			String msg = IberErrorsMsgConstants.UNEXPECTED_MSG;
			if (ex.getMessage() != null && !"".equals(ex.getMessage())) {
				msg = ex.getMessage();
			}
			logger.error("Error", ex);
			response.sendError(HttpServletResponse.SC_NOT_ACCEPTABLE,
					messageErrorsSource.getMessage(msg, null, locale));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
