package me.chyxion.tigon.webmvc.exception;

import java.util.List;
import java.util.ArrayList;
import me.chyxion.tigon.webmvc.JSONViewDataModel;
import org.springframework.core.annotation.Order;
import org.springframework.validation.FieldError;
import org.springframework.validation.BindException;
import org.springframework.validation.BindingResult;
import me.chyxion.tigon.exception.InvalidParamException;
import org.springframework.web.bind.MethodArgumentNotValidException;

/**
 * @version 0.0.1
 * @since 0.0.3
 * @author Shaun Chyxion <br>
 * chyxion@163.com <br>
 * Feb 3, 2015 1:44:09 PM
 */
@Order(8)
public class BindingResultResolver implements ExceptionResolver {

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean accept(Throwable ex) {
        return ex instanceof MethodArgumentNotValidException || 
                ex instanceof BindException;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public JSONViewDataModel process(JSONViewDataModel model) {
        Throwable e = model.getException();
        BindingResult br = null;
        if (e instanceof MethodArgumentNotValidException) {
            br = ((MethodArgumentNotValidException) e).getBindingResult();
        }
        else if (e instanceof BindException) {
            br = ((BindException) e).getBindingResult();
        }
        if (br != null) {
            List<FieldError> fieldErrors = br.getFieldErrors();
            final List<String> messages = new ArrayList<String>(fieldErrors.size());
            for (FieldError er : fieldErrors) {
                messages.add("'" + er.getField() + "' " + er.getDefaultMessage());
            }
            model.setMessage(messages);
        }
        model.setCode(InvalidParamException.CODE);
        return model;
    }
}
