package com.atlassian.stash.internal.rest.user;

import com.atlassian.bitbucket.rest.RestErrorMessage;
import com.atlassian.bitbucket.rest.RestErrors;
import com.atlassian.bitbucket.rest.util.ResponseFactory;
import com.atlassian.bitbucket.rest.util.RestUtils;
import com.google.common.base.Throwables;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import javax.validation.Validator;
import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;

import static javax.ws.rs.core.Response.Status.BAD_REQUEST;

public final class Validators {

    public static void validateConstraints(Validator validator, Object object) {
        List<ConstraintViolation<?>> validationErrors = new ArrayList<ConstraintViolation<?>>(validator.validate(object));
        Collections.sort(validationErrors, new ConstraintViolationComparator());
        if (!validationErrors.isEmpty()) {
            throw new ConstraintViolationException(new LinkedHashSet<>(validationErrors));
        }
    }

    public static Response reportAsConstraintViolation(Object object, String field, String message) {
        RestErrorMessage error = new RestErrorMessage(getField(object, field), message);
        RestErrors errors = new RestErrors(error);
        return ResponseFactory.status(BAD_REQUEST).entity(errors).type(RestUtils.APPLICATION_JSON_UTF8).build();
    }

    private static String getField(Object object, String field) {
        try {
            return object.getClass().getDeclaredField(field).getName();
        } catch (NoSuchFieldException e) {
            throw Throwables.propagate(e);
        }
    }
}
