package cn.reghao.oss.console.util.validator;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 验证枚举值是否有效
 *
 * @author reghao
 * @date 2021-06-21 17:36:03
 */
@Slf4j
public class EnumValidator implements ConstraintValidator<ValidEnum, Object> {
    private final List<Object> values = new ArrayList<>();

    /**
     * 第一次校验数据时初始化，只在初始化时调用一次
     *
     * @param
     * @return
     * @date 2021-06-21 下午7:01
     */
    @Override
    public void initialize(ValidEnum constraintAnnotation) {
        Class<?> enumClazz = constraintAnnotation.value();
        Object[] enumConstants = enumClazz.getEnumConstants();
        if (enumConstants == null) {
            return;
        }

        Method method = BeanUtils.findMethod(enumClazz, constraintAnnotation.method());
        if (method == null) {
            log.error("枚举对象:[{}]中不存在方法:[{}],请检查.", enumClazz.getName(), constraintAnnotation.method());
            return;
        }

        method.setAccessible(true);
        try {
            for (Object enumConstant : enumConstants) {
                values.add(method.invoke(enumConstant));
            }
        } catch (Exception e) {
            log.error("获取枚举类:[{}]的枚举对象的值失败.", enumClazz);
        }
    }

    /**
     * 每次校验数据时调用
     *
     * @param
     * @return
     * @date 2021-06-21 下午7:02
     */
    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        return value == null || values.contains(value);
    }
}
