package com.mmc.iuav.user.model.vo.dronepilot;

/**
 * @Author small
 * @Date 2023/7/29 9:47
 * @Version 1.0
 */


import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Target({ElementType.METHOD, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = EnumValue.Validator.class)
public @interface EnumValue {
    String message() default "{custom.value.invalid}";

    boolean nullable() default false;

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    Class<? extends BaseEnum> enumClass();

    class Validator implements ConstraintValidator<EnumValue, Object> {

        private Class<? extends BaseEnum> enumClass;
        boolean nullable = false;

        @Override
        public void initialize(EnumValue enumValue) {
            enumClass = enumValue.enumClass();
            nullable = enumValue.nullable();
        }

        @Override
        public boolean isValid(Object value, ConstraintValidatorContext constraintValidatorContext) {
            if (value == null && nullable) {
                return Boolean.TRUE;
            }

            if (value == null && !nullable) {
                return Boolean.FALSE;
            }

            if (enumClass == null) {
                return Boolean.TRUE;
            }

            String enumCode = (String) value;
            return EnumUtils.isValidCode(enumClass, enumCode);
        }
    }
}
