package com.njzscloud.common.mvc.validator;

import cn.hutool.core.util.StrUtil;

import javax.validation.ConstraintValidatorContext;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ConstraintValidator implements javax.validation.ConstraintValidator<Constraint, Constrained> {

    @Override
    public boolean isValid(Constrained valid, ConstraintValidatorContext ctx) {
        ValidRule[] rules = valid.rules();

        if (rules == null || rules.length == 0) return true;

        List<String> messageList = Arrays.stream(rules)
                .filter(it -> !it.predicate.get())
                .map(it -> it.message)
                .collect(Collectors.toList());

        if (messageList.isEmpty()) return true;

        ctx.disableDefaultConstraintViolation();
        ctx.buildConstraintViolationWithTemplate(StrUtil.join(";\n", messageList))
                .addConstraintViolation();

        return false;
    }
}
