/*
 * Queue - A Queueing system that can be used to handle labs in higher education
 * Copyright (C) 2016-2021  Delft University of Technology
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <https://www.gnu.org/licenses/>.
 */
package nl.tudelft.queue.controller;

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

import nl.tudelft.librador.exception.DTOValidationException;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.reactive.function.client.WebClientResponseException;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;

/**
 * Controller advice class. This class is used to handle exceptions that get thrown during request handling
 * procedures. Such errors include, but are not limited to 404 errors and 403 errors. This class defines the
 * procedures that help give the user a sensible error page when something goes wrong.
 */
@ControllerAdvice
public class ErrorControllerAdvice extends ResponseEntityExceptionHandler {
	private static final Logger logger = LoggerFactory.getLogger(ErrorControllerAdvice.class);

	/**
	 * Handles a BAD_REQUEST exception occurring within the server. This is an exception that occurs when a
	 * developer did not watch their parameter naming or request handling properly.
	 *
	 * @return The thymeleaf template to resolve.
	 */
	@ResponseStatus(HttpStatus.BAD_REQUEST)
	@ExceptionHandler(WebClientResponseException.BadRequest.class)
	public String handleBadRequestException(Exception e) {
		logger.warn("Request caused a BAD_REQUEST (400) error.", e);

		return "error/400";
	}

	/**
	 * Handles a FORBIDDEN exception occurring within the server. This method simply logs the event and
	 * redirects the user to a 403 specific error page.
	 *
	 * @return The thymeleaf template to be filled out.
	 */
	@ResponseStatus(HttpStatus.FORBIDDEN)
	@ExceptionHandler(AccessDeniedException.class)
	public String handleDeniedException() {
		return "error/403";
	}

	/**
	 * Handles a NOT FOUND exception occurring within the server. This method simply logs the event and
	 * redirects the user to a 404 specific error page.
	 *
	 * @return The thymeleaf template to be filled out.
	 */
	@ResponseStatus(HttpStatus.NOT_FOUND)
	@ExceptionHandler(EntityNotFoundException.class)
	public String handle404Exception() {
		return "error/404";
	}

	/**
	 * Handles an UNPROCESSABLE ENTITY exception occurring within the server. This method simply redirects the
	 * user to a 422 specific error page.
	 *
	 * @return The thymeleaf template to be resolved.
	 */
	@ResponseStatus(HttpStatus.UNPROCESSABLE_ENTITY)
	@ExceptionHandler(DTOValidationException.class)
	public String handle422Exception() {
		return "error/422";
	}

	/**
	 * Handles a {@link DataIntegrityViolationException} exception occurring within the server. These usually
	 * occur when front-end data validation fails to find an error in input data. This method simply logs the
	 * event and redirects the user to a generic error page.
	 *
	 * @param  e The exception that was thrown, causing this method to be triggered.
	 * @return   The thymeleaf template to be filled out.
	 */
	@ExceptionHandler(DataIntegrityViolationException.class)
	public String handleSQLException(Exception e) {
		logger.error("An SQL error occurred", e);

		return "error/500";
	}

	@ExceptionHandler(ResponseStatusException.class)
	public String handleResponseStatusException(ResponseStatusException e,
			HttpServletRequest req, HttpServletResponse resp,
			Model model) throws Exception {
		resp.setStatus(e.getStatus().value());

		switch (e.getStatus()) {
			case FORBIDDEN:
				return handleDeniedException();
			case NOT_FOUND:
				return handle404Exception();
			case UNPROCESSABLE_ENTITY:
				return handle422Exception();
			default:
				return defaultErrorHandler(req, e, model);
		}
	}

	/**
	 * Handles any non-specific exception. This method checks the specific exception for the
	 * {@link ResponseStatus} annotation. If a {@link ResponseStatus} annotation is found, the exception is
	 * off-handed to Spring to handle. Otherwise, a generic error page is setup.
	 *
	 * @param  request   The request actually performed to cause the exception.
	 * @param  e         The exception that was thrown, causing this method to be triggered.
	 * @param  model     The model to fill out for Thymeleaf template resolution.
	 * @return           The Thymeleaf template to resolve.
	 * @throws Exception when the exception is redirected to Spring to handle.
	 */
	@ExceptionHandler(Exception.class)
	public String defaultErrorHandler(HttpServletRequest request, Exception e, Model model) throws Exception {
		logger.error("A Request ({}) raised an exception", request.getRequestURI(), e);

		// If the exception is annotated with @ResponseStatus rethrow it and let
		// the framework handle it - like the OrderNotFoundException example
		// at the start of this post.
		// AnnotationUtils is a Spring Framework utility class.
		if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null)
			throw e;

		// Otherwise setup and send the user to a default error-view.
		model.addAttribute("exception", e);
		model.addAttribute("url", request.getRequestURL());

		return "error/500";
	}

	/**
	 * Redirects any leftover requests for the /error page to the default error handler.
	 *
	 * @param  request   The request that was made causing an exception to be thrown.
	 * @param  e         The exception that was thrown.
	 * @param  model     The model to use during Thymleaf resolution.
	 * @return           The Thymeleaf template to resolve.
	 * @throws Exception when an Exception is rethrown to be handled by Spring.
	 */
	@GetMapping("/error")
	public String defaultErrorMappingHandler(HttpServletRequest request, Exception e, Model model)
			throws Exception {
		return defaultErrorHandler(request, e, model);
	}
}
