package io.geekidea.springbootplus.framework.signature;

import java.util.Iterator;
import java.util.Optional;
import java.util.Set;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;

import org.hibernate.validator.HibernateValidator;

/**
 *
 * @Author linux
 * @Date 2021年01月20日 18:18
 * @Version 1.0
 */
public class ValidatorUtils {

    private final static Validator VALIDATOR_FAST =
            Validation.byProvider(HibernateValidator.class).configure().failFast(true).buildValidatorFactory().getValidator();
    private final static Validator VALIDATOR_ALL =
            Validation.byProvider(HibernateValidator.class).configure().failFast(false).buildValidatorFactory().getValidator();

    /**
     * 校验遇到第一个不合法的字段直接返回不合法字段，后续字段不再校验
     * @Time 2020年6月22日 上午11:36:13
     * @param <T>
     * @param domain
     * @return
     */
    public static <T> Optional<String> validateFast(T domain) {
        Set<ConstraintViolation<T>> validateResult = VALIDATOR_FAST.validate(domain);
        if (validateResult.size() > 0) {
            System.out.println(validateResult.iterator().next().getPropertyPath() + "：" + validateResult.iterator().next().getMessage());
        }

        StringBuilder sb = new StringBuilder();
        for (Iterator<ConstraintViolation<T>> iterator = validateResult.iterator(); iterator.hasNext(); ) {
            sb.append(iterator.next().getMessage());
            if (iterator.hasNext()) {
                sb.append(" ,");
            }
        }
        return Optional.of(sb.toString());

    }

    /**
     * 校验所有字段并返回不合法字段
     * @Time 2020年6月22日 上午11:36:55
     * @param <T>
     * @param domain
     * @return
     */
    public static <T> Optional<String> validateAll(T domain) {
        Set<ConstraintViolation<T>> validateResult = VALIDATOR_ALL.validate(domain);
        if (validateResult.size() > 0) {
            for (ConstraintViolation<T> cv : validateResult) {
                System.out.println(cv.getPropertyPath() + "：" + cv.getMessage());
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Iterator<ConstraintViolation<T>> iterator = validateResult.iterator(); iterator.hasNext(); ) {
            sb.append(iterator.next().getMessage());
            if (iterator.hasNext()) {
                sb.append(" ,");
            }
        }
        return Optional.of(sb.toString());
    }
}
