/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.actionbazaar.interfaces.rest;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;
import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.ext.ExceptionMapper;
import javax.ws.rs.ext.Provider;

@Provider
public class ValidationExceptionMapper implements ExceptionMapper<ConstraintViolationException> {

    private final Logger logger = Logger.getLogger(ValidationExceptionMapper.class.getSimpleName());

    public ValidationExceptionMapper() {
        logger.severe("constructor called");
    }

    @Override
    public Response toResponse(javax.validation.ConstraintViolationException ex) {

        logger.info("Exception received: " + ex.toString());
        logger.throwing(null, null, ex);
        
        Map<String, String> errors = new HashMap<>();
        
        // Iterate over constraint violations and put into error map
        for(ConstraintViolation<?> c: ex.getConstraintViolations()) {
            errors.put(c.getMessage(), c.getInvalidValue().toString());
        }
        
        return Response.status(Status.PRECONDITION_FAILED)
                .entity(errors)
                .type(MediaType.TEXT_PLAIN)
                .build();
    }
}
