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.config.ProxyConfig;
import quant.rich.emoney.interfaces.IConfig;

public class ProxyConfigValidator implements IValidator, ConstraintValidator<ProxyConfigValid, IConfig<ProxyConfig>> {

    @Override
    public boolean isValid(IConfig<ProxyConfig> value, ConstraintValidatorContext context) {
        
        if (value == null) return true;
        if (!(value instanceof ProxyConfig config)) return true;
        
        if (config.getProxyType() != null && config.getProxyType() != Proxy.Type.DIRECT) {
            if (StringUtils.isBlank(config.getProxyHost())) {
                return invalid(context, "设置代理为 HTTP 或 SOCKS 时，代理地址不允许为空");
            }
            if (Objects.isNull(config.getProxyPort()) || config.getProxyPort() <= 0 || config.getProxyPort() > 65535) {
                return invalid(context, "端口不合法");
            }
            // 非匿名须判断用户名密码是否为空
            boolean valid = ProxyConfig.isProxyEffective(
                    config.getProxy(), config.getIgnoreHttpsVerification());
            if (!valid) {
                return invalid(context, "代理连接失败，请检查");
            }
        }
        
        return true;
        
    }

}
