package com.eactive.eai.rms.common.exception;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Optional;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.servlet.ModelAndView;

@ControllerAdvice
public class GlobalExceptionController {

	protected final Logger logger = LoggerFactory.getLogger(GlobalExceptionController.class);

	@ExceptionHandler(Exception.class)
	public ModelAndView handleAllException(Exception e, HttpServletRequest request, HttpServletResponse response) {
		logger.error("GlobalExceptionController] handleAllException", e);
		response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
		String errMsg = e.getMessage();

		// DB Insert 중 무결성(중복) 체크
		if (e instanceof DuplicateKeyException) {
			errMsg = Optional
					.ofNullable((SQLException) ((DataAccessException) e).getRootCause())
					.map(SQLException::getMessage)
					.orElse("");
			errMsg = errMsg + "중복 KEY 에러발생.\n자세한 사항은 관리자에게 문의바랍니다. ";
		}

		if (request.getServletPath().endsWith(".json")) {
			HashMap resultMap = new HashMap();
			resultMap.put("status", "fail");
			resultMap.put("errorMsg", errMsg);
			ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
			return modelAndView;
		} else {
			return null;
		}
	}

	@ExceptionHandler(RuntimeException.class)
	public ModelAndView handleBizException(Exception e, HttpServletRequest request, HttpServletResponse response) {
		logger.error("GlobalExceptionController] handleBizException ", e);
		response.setStatus(HttpServletResponse.SC_BAD_REQUEST);

		if (request.getServletPath().endsWith(".json")) {
			HashMap resultMap = new HashMap();
			resultMap.put("status", "fail");
			resultMap.put("errorMsg", e.getMessage());
			ModelAndView modelAndView = new ModelAndView("jsonView", resultMap);
			return modelAndView;
		} else {
			return null;
		}
	}

}