package com.changhu.common.validator;

import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.changhu.common.validator.annotation.OnlyInValue;
import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;

/**
 * author: luozhun
 * desc: OnlyInValueValidator
 * createTime: 2023/8/22 9:40
 */
public class OnlyInValueValidator implements ConstraintValidator<OnlyInValue, Object> {
    private boolean required = false;
    private String[] strValues;
    private int[] intValues;

    @Override
    public void initialize(OnlyInValue constraintAnnotation) {
        required = constraintAnnotation.required();
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        if (required) {
            return valid(value);
        } else {
            if (ObjectUtil.isNull(value)) {
                return true;
            } else {
                return valid(value);
            }
        }
    }

    private boolean valid(Object value) {
        if (value instanceof String) {
            for (String str : strValues) {
                if (StrUtil.equals(str, value + "")) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (int num : intValues) {
                if (NumberUtil.equals(num, (int) value)) {
                    return true;
                }
            }
        }
        return false;
    }

}
