package com.luomu.scaffold.controller.support;

import java.io.IOException;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import com.luomu.scaffold.service.support.PlatformException;

@ControllerAdvice
public class ControllerSupport {

	private static final Logger log = LoggerFactory.getLogger(ControllerSupport.class);

	@ExceptionHandler(RuntimeException.class)
	@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
	public void pageRenderException(HttpServletRequest request, HttpServletResponse response, Exception ex)
			throws IOException, ServletException {

		log.error(ex.getLocalizedMessage());
		if (isAjax(request)) {
			writeResponse(response, "{\"code\":500,\"msg\":\"服务器错误\"}");
		} else {
			response.setStatus(HttpStatus.UNAUTHORIZED.value());
			request.getRequestDispatcher("/error/error").forward(request, response);
		}
	}

	@ResponseBody
	@ExceptionHandler(PlatformException.class)
	public JsonResult platformAutoRenderResult(PlatformException ex) {

		log.error(ex.getLocalizedMessage());
		return new JsonResult().setSuccess(false).setCode(ex.getCode()).setMessage(ex.getLocalizedMessage());
	}

	@ExceptionHandler(UnauthenticatedException.class)
	public String unauthenticatedException() {
		return "redirect:/system/login";
	}

	private boolean isAjax(HttpServletRequest request) {
		return "XMLHttpRequest".equalsIgnoreCase(request.getHeader("x-requested-with"));
	}

	private void writeResponse(HttpServletResponse response, String msg) throws IOException {
		response.setCharacterEncoding("utf-8");
		response.getWriter().write(msg);
	}
}
