package jp.kobe_u.cs27.newse.medicalcheck.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import jp.kobe_u.cs27.newse.medicalcheck.exception.MedicalCheckException;
import lombok.Data;

@RestControllerAdvice
public class MedicalCheckExceptionHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<ErrorMessage> handleException(HttpServletRequest req, MethodArgumentNotValidException ex) {
        return handleException(req, new MedicalCheckException(MedicalCheckException.FORM_VALIDATION_FAILED,
                "Form validation failed. Please check the parameters: " + ex.getMessage(), ex));
    }


    @ExceptionHandler(MedicalCheckException.class)
    public ResponseEntity<ErrorMessage> handleException(HttpServletRequest req, MedicalCheckException ex) {
        switch (ex.getCode()) {
            case MedicalCheckException.NO_SUCH_PERSON:
                return new ResponseEntity<ErrorMessage>(new ErrorMessage(ex), HttpStatus.NOT_FOUND);
            default:
                return new ResponseEntity<ErrorMessage>(new ErrorMessage(ex), HttpStatus.BAD_REQUEST);
        }
    }



    @Data
    public class ErrorMessage {
        private String code;
        private String message;

        public ErrorMessage(MedicalCheckException e) {
            this.code = String.format("E%02d", e.getCode());
            this.message = e.getMessage();
        }
    }

}