package quant.rich.emoney.validator;

import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import quant.rich.emoney.entity.config.DeviceInfoConfig;
import quant.rich.emoney.entity.config.EmoneyRequestConfig;
import quant.rich.emoney.interfaces.IConfig;

public class EmoneyRequestConfigValidator implements IValidator, ConstraintValidator<EmoneyRequestConfigValid, IConfig<EmoneyRequestConfig>> {

    static final Pattern androidIdPattern = Pattern.compile("^[0-9a-f]{16}$");
    
    @Override
    public boolean isValid(IConfig<EmoneyRequestConfig> value, ConstraintValidatorContext context) {
        
        if (value == null) return true;
        if (!(value instanceof EmoneyRequestConfig config)) return true;
        
        if (!config.getIsAnonymous()) {
            // 非匿名须判断用户名密码是否为空
            if (StringUtils.isAnyBlank(config.getUsername(), config.getPassword())) {
                context.disableDefaultConstraintViolation();
                context.buildConstraintViolationWithTemplate("配置非匿名时用户名和密码不能为空")
                       .addConstraintViolation();
                return false;
            }
        }
        
        if (!androidIdPattern.matcher(config.getAndroidId()).matches()) {
            // 判断 androidId 合法性
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("非法的 Android Id，必须是 16 位十六进制小写字符串")
                   .addConstraintViolation();
            return false;
        }
        
        if (!DeviceInfoConfig.DeviceInfo.PATTERN.matcher(config.getFingerprint()).matches()) {
            context.disableDefaultConstraintViolation();
            context.buildConstraintViolationWithTemplate("非法的 Fingerprint")
                   .addConstraintViolation();
            return false;
        }
        
        return true;
        
    }

}
