package xyz.wbsite.frame.validation;

import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;
import xyz.wbsite.frame.utils.StringUtil;

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

public class NumberValidator implements ConstraintValidator<Number, Integer> {

    private int min;
    private int max;
    private String defaultMessage;

    @Override
    public void initialize(Number constraint) {
        min = constraint.min();
        max = constraint.max();
    }

    @Override
    public boolean isValid(Integer o, ConstraintValidatorContext constraintValidatorContext) {
        String fieldName = "";
        if (constraintValidatorContext instanceof ConstraintValidatorContextImpl) {
            ConstraintValidatorContextImpl validatorContext = (ConstraintValidatorContextImpl) constraintValidatorContext;
            if (validatorContext.getConstraintViolationCreationContexts() != null
                    && validatorContext.getConstraintViolationCreationContexts().size() > 0
                    && validatorContext.getConstraintViolationCreationContexts().get(0).getPath() != null) {
                fieldName = validatorContext.getConstraintViolationCreationContexts().get(0).getPath().asString();
            }
        }

        if (o < min) {
            constraintValidatorContext.disableDefaultConstraintViolation();
            String message = StringUtil.isNotEmpty(defaultMessage) ? defaultMessage : String.format(Locale.CHINESE, "[ %s ] 最小值为%d！", fieldName, min);
            constraintValidatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
            return false;
        } else if (o > max) {
            constraintValidatorContext.disableDefaultConstraintViolation();
            String message = StringUtil.isNotEmpty(defaultMessage) ? defaultMessage : String.format(Locale.CHINESE, "[ %s ] 最大值为%d！", fieldName, max);
            constraintValidatorContext.buildConstraintViolationWithTemplate(message).addConstraintViolation();
            return false;
        } else {
            return true;
        }
    }
}
