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.sqlite.RequestInfo;
import quant.rich.emoney.interfaces.IValidator;

public class RequestInfoValidator implements IValidator, ConstraintValidator<RequestInfoValid, RequestInfo> {

    static final Pattern androidIdPattern = Pattern.compile("^[0-9a-f]{16}$");
    
    @Override
    public boolean isValid(RequestInfo value, ConstraintValidatorContext context) {
        
        if (value == null) return true;
        if (!(value instanceof RequestInfo config)) return true;
        
        // 如果有用户名则必须设置密码
        if (!StringUtils.isBlank(config.getUsername()) && StringUtils.isBlank(config.getPassword())) {
            return invalid(context, "当设置了用户名时，必须提供密码");
        }
        
        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;
        
    }

}
