package eu.dnetlib.uoaadmintools.handlers;

import eu.dnetlib.uoaadmintools.responses.ExceptionResponse;

import org.apache.log4j.Logger;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import java.util.Date;

@ControllerAdvice
public class ExceptionsHandler {
    private final Logger log = Logger.getLogger(this.getClass());

    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseEntity<ExceptionResponse> invalidInput(Exception ex) {
        ExceptionResponse response = new ExceptionResponse();
        response.setErrorCode("Validation Error");
        response.setErrorMessage("Invalid inputs.");
        response.setErrors(ex.getMessage());
        log.debug("invalidInput exception");

        return new ResponseEntity<ExceptionResponse>(response, HttpStatus.BAD_REQUEST);
    }
    @ExceptionHandler(ContentNotFoundException.class)
    public ResponseEntity<ErrorDetails> contentNotFound(Exception ex) {
        ExceptionResponse response = new ExceptionResponse();
        response.setErrorCode("No content found");
        response.setErrorMessage(ex.getMessage());
        response.setErrors(ex.getMessage());
        ErrorDetails errorDetails = new ErrorDetails(new Date(),ex.getMessage(),ex.getMessage());
        log.debug("contentNotFound exception" + response.getErrorCode()+ " "+response.getErrorMessage());

        return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.NOT_FOUND);
    }
    @ExceptionHandler(NullPointerException.class)
    public ResponseEntity<ExceptionResponse> nullPointerException(Exception ex) {
        ExceptionResponse response = new ExceptionResponse();
        response.setErrorCode("Null pointer Exception");
        response.setErrorMessage("Null pointer Exception");
        response.setErrors(ex.getMessage());
        log.debug("nullPointerException exception");
        return new ResponseEntity<ExceptionResponse>(response, HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(InvalidReCaptchaException.class)
    public ResponseEntity<ExceptionResponse> invalidReCaptchaException(Exception ex) {
        ExceptionResponse response = new ExceptionResponse();
        response.setErrorCode("Invalid ReCaptcha Exception");
        response.setErrorMessage("Invalid ReCaptcha Exception");
        response.setErrors(ex.getMessage());
        log.debug("invalidReCaptchaException exception");
        return new ResponseEntity<ExceptionResponse>(response, HttpStatus.BAD_REQUEST);
    }
}
