package me.chyxion.tigon.webmvc.exception;

import java.util.Set;
import java.util.List;
import java.util.ArrayList;
import lombok.extern.slf4j.Slf4j;
import javax.validation.ConstraintViolation;
import org.springframework.core.annotation.Order;
import me.chyxion.tigon.webmvc.JSONViewDataModel;
import javax.validation.ConstraintViolationException;
import me.chyxion.tigon.exception.InvalidParamException;

/**
 * @version 0.0.1
 * @since 0.0.1
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Mar 28, 2016 6:39:36 PM
 */
@Slf4j
@Order(10)
public class ConstraintViolationExceptionResolver implements ExceptionResolver {

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean accept(final Throwable ex) {
        return ex instanceof ConstraintViolationException;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public JSONViewDataModel process(final JSONViewDataModel model) {
        final Set<ConstraintViolation<?>> cvs =
            ((ConstraintViolationException) model.getException()).getConstraintViolations();
        final List<String> messages = new ArrayList<String>(cvs.size());
        for (ConstraintViolation<?> cv : cvs) {
            log.info("Constraint violation [{}] Caused.", cv);
            messages.add("'" + cv.getPropertyPath() + "' " + cv.getMessage());
        }
        model.setCode(InvalidParamException.CODE);
        model.setMessage(messages);
        return model;
    }
}
