package me.chyxion.tigon.webmvc.exception;

import java.util.Set;
import java.util.List;
import org.slf4j.Logger;
import java.util.ArrayList;
import org.slf4j.LoggerFactory;
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
 */
@Order(10)
public class ConstraintViolationExceptionResolver implements ExceptionResolver {
	private static final Logger log = 
		LoggerFactory.getLogger(ConstraintViolationExceptionResolver.class);

	/**
	 * {@inheritDoc}
	 */
	@Override
	public boolean accept(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;
	}
}
