package xyz.wbsite.dbtool.web.frame.validation;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.HashSet;

public class DictValidator implements ConstraintValidator<Dict, String> {

    private String name;

    @Override
    public void initialize(Dict constraint) {
        name = constraint.name();
    }

    @Override
    public boolean isValid(String o, ConstraintValidatorContext constraintValidatorContext) {
        if (null == o) {
            return true;
        } else if (name == null) {
            constraintValidatorContext.disableDefaultConstraintViolation();
            constraintValidatorContext.buildConstraintViolationWithTemplate("字典名称为空").addConstraintViolation();
            return false;
        } else {
            // name 字典名称
            HashSet<String> codeSet = new HashSet<>();
            if (codeSet.contains(o)) {
                return true;
            } else {
                constraintValidatorContext.disableDefaultConstraintViolation();
                constraintValidatorContext.buildConstraintViolationWithTemplate("非法的字典[" + name + "]值").addConstraintViolation();
                return false;
            }
        }
    }
}
