package quant.rich.emoney.validator;

import java.net.Proxy;
import java.util.Objects;
import org.apache.commons.lang3.StringUtils;

import jakarta.validation.ConstraintValidator;
import jakarta.validation.ConstraintValidatorContext;
import quant.rich.emoney.entity.sqlite.ProxySetting;
import quant.rich.emoney.interfaces.IValidator;

public class ProxySettingValidator implements IValidator, ConstraintValidator<ProxySettingValid, ProxySetting> {

    @Override
    public boolean isValid(ProxySetting value, ConstraintValidatorContext context) {
        
        if (value == null) return true;
        if (!(value instanceof ProxySetting proxySetting)) return true;
        
        if (proxySetting.getProxyType() != null && proxySetting.getProxyType() != Proxy.Type.DIRECT) {
            if (StringUtils.isBlank(proxySetting.getProxyHost())) {
                return invalid(context, "设置代理为 HTTP 或 SOCKS 时，代理地址不允许为空");
            }
            if (Objects.isNull(proxySetting.getProxyPort()) || proxySetting.getProxyPort() <= 0 || proxySetting.getProxyPort() > 65535) {
                return invalid(context, "端口不合法");
            }
            // 不做连通性校验：有的代理可能先添加后生效
        }
        
        return true;
        
    }

}
