package com.wecloud.im.core.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.wecloud.im.core.common.enums.BaseEnum;
import com.wecloud.im.core.common.exception.BusinessException;
import com.wecloud.im.core.util.BaseEnumUtil;
import com.wecloud.im.core.validator.constraints.EnumType;

/**
 * 自定义系统内的枚举验证注解实现类
 *
 * @author geekidea
 * @date 2018-11-08
 */
public class EnumTypeValidator implements ConstraintValidator<EnumType, Integer> {

    private Class<? extends BaseEnum> baseEnum;

    @Override
    public void initialize(EnumType parameters) {
        baseEnum = parameters.type();
        if (baseEnum == null) {
            throw new BusinessException("请传入枚举类型类");
        }
    }

    @Override
    public boolean isValid(Integer value, ConstraintValidatorContext constraintValidatorContext) {
        if (value == null) {
            return true;
        }
        return BaseEnumUtil.exists(baseEnum, value);
    }
}
