package org.batfish.datamodel;

import org.batfish.datamodel.visitors.GenericIpSpaceVisitor;

/**
 * An {@link GenericIpSpaceVisitor IpSpace visitor} that tests if the {@link IpSpace} contains an
 * {@link Ip}. Implementation of {@link IpSpaceReference} is left abstract.
 */
public abstract class AbstractIpSpaceContainsIp implements GenericIpSpaceVisitor<Boolean> {
  private final Ip _ip;

  public AbstractIpSpaceContainsIp(Ip ip) {
    _ip = ip;
  }

  @Override
  public final Boolean castToGenericIpSpaceVisitorReturnType(Object o) {
    return (Boolean) o;
  }

  @Override
  public final Boolean visitAclIpSpace(AclIpSpace aclIpSpace) {
    return aclIpSpace.getLines().stream()
        .filter(line -> line.getIpSpace().accept(this))
        .map(AclIpSpaceLine::getAction)
        .findFirst()
        .map(action -> action == LineAction.PERMIT)
        .orElse(false);
  }

  @Override
  public final Boolean visitEmptyIpSpace(EmptyIpSpace emptyIpSpace) {
    return false;
  }

  @Override
  public final Boolean visitIpIpSpace(IpIpSpace ipIpSpace) {
    return _ip.equals(ipIpSpace.getIp());
  }

  @Override
  public final Boolean visitIpWildcardIpSpace(IpWildcardIpSpace ipWildcardIpSpace) {
    return ipWildcardIpSpace.getIpWildcard().containsIp(_ip);
  }

  @Override
  public final Boolean visitIpWildcardSetIpSpace(IpWildcardSetIpSpace ipWildcardSetIpSpace) {
    return ipWildcardSetIpSpace.getBlacklist().stream().noneMatch(w -> w.containsIp(_ip))
        && ipWildcardSetIpSpace.getWhitelist().stream().anyMatch(w -> w.containsIp(_ip));
  }

  @Override
  public final Boolean visitPrefixIpSpace(PrefixIpSpace prefixIpSpace) {
    return prefixIpSpace.getPrefix().containsIp(_ip);
  }

  @Override
  public final Boolean visitUniverseIpSpace(UniverseIpSpace universeIpSpace) {
    return true;
  }
}

@@ -647,70 +647,70 @@
     
-return aclIpSpace.getLines().stream()%0A        .filter(line -%3E 
+for (AclIpSpaceLine line : aclIpSpace.getLines()) %7B%0A      if (
 line
@@ -736,16 +736,18 @@
 t(this))
+ %7B
 %0A       
@@ -751,29 +751,20 @@
     
-.map(AclIpSpaceLine::
+return line.
 getA
@@ -772,60 +772,10 @@
 tion
+(
 )
-%0A        .findFirst()%0A        .map(action -%3E action
  == 
@@ -795,32 +795,40 @@
 RMIT
-)
+;
 %0A      
-  .orElse(
+%7D%0A    %7D%0A    return 
 false
-)
 ;%0A  
@@ -1321,38 +1321,51 @@
 tIpSpace) %7B%0A    
-return
+for (IpWildcard w :
  ipWildcardSetIp
@@ -1388,33 +1388,22 @@
 st()
-.stream().noneMatch(w -%3E 
+) %7B%0A      if (
 w.co
@@ -1416,16 +1416,18 @@
 Ip(_ip))
+ %7B
 %0A       
@@ -1431,88 +1431,181 @@
     
-&& ipWildcardSetIpSpace.getWhitelist().stream().anyMatch(w -%3E w.containsIp(_ip))
+return false;%0A      %7D%0A    %7D%0A    for (IpWildcard w : ipWildcardSetIpSpace.getWhitelist()) %7B%0A      if (w.containsIp(_ip)) %7B%0A        return true;%0A      %7D%0A    %7D%0A    return false
 ;%0A  

rewrite using for loops (#5939)