package com.ejie.ad74a.handler;

import java.io.IOException;

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

import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ejie.ad74a.exceptions.Ad74aException;
import com.ejie.ad74a.exceptions.ValidatorException;
import com.ejie.ad74a.helper.ErroresViewHelper;

public class Ad74aExceptionHandler {

	// Parametro de la respuesta de Ajax
	private static final String RESPUESTA_AJAX = "X-Requested-With";

	@Resource
	private ReloadableResourceBundleMessageSource appMessageSource;

	@ExceptionHandler(value = Ad74aException.class)
	public @ResponseBody String handle(Ad74aException ad74aException, HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		String msg = ad74aException.getMessage();
		String masDetalle = "";

		if (ad74aException instanceof ValidatorException) {
			ValidatorException validatorException = (ValidatorException) ad74aException;
			masDetalle = ErroresViewHelper.obtenerErrorRup(this.appMessageSource, validatorException.getErrorsFields());

		}

		if (masDetalle != null && !masDetalle.isEmpty()) {
//			msg = msg.concat(
//					"<br><span class='masDetalleErrorSpan'><i class='fa fa-info'></i> <a onclick='$(\".masDetalleErrorContent\").toogle();' class='masDetalleErrorLink'>")
//					.concat(this.appMessageSource.getMessage("verDetalle", null, LocaleContextHolder.getLocale()))
//					.concat("</a></span>").concat("<div class='masDetalleErrorContent' style='display:none;'>")
//					.concat(masDetalle).concat("</div>");

			msg = masDetalle;
		}
		resp.setStatus(HttpStatus.BAD_REQUEST.value());
		// Writer w = null;

//		w = resp.getWriter();
//		w.write(msg);
//		w.flush();
		return msg;
	}

	/*
	 * @Bean public HttpMessageConverter<String> responseBodyConverter() {
	 * StringHttpMessageConverter converter = new StringHttpMessageConverter();
	 * converter.setSupportedMediaTypes(Arrays.asList(new MediaType("text", "plain",
	 * Charset.forName("UTF-8")))); return converter; }
	 */
}
