package org.batfish.specifier;

import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import org.batfish.datamodel.AclIpSpace;
import org.batfish.datamodel.IpWildcard;
import org.batfish.referencelibrary.AddressGroup;

/** An {@link IpSpaceSpecifier} that is looks up the IpSpace from the reference book. */
public final class ReferenceAddressGroupIpSpaceSpecifier implements IpSpaceSpecifier {
  private final String _addressGroupName;
  private final String _bookName;

  public ReferenceAddressGroupIpSpaceSpecifier(String addressGroupname, String bookName) {
    _addressGroupName = addressGroupname;
    _bookName = bookName;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (!(o instanceof ReferenceAddressGroupIpSpaceSpecifier)) {
      return false;
    }
    return Objects.equals(
            _addressGroupName, ((ReferenceAddressGroupIpSpaceSpecifier) o)._addressGroupName)
        && Objects.equals(_bookName, ((ReferenceAddressGroupIpSpaceSpecifier) o)._addressGroupName);
  }

  @Override
  public int hashCode() {
    return Objects.hash(_addressGroupName, _bookName);
  }

  @Override
  public IpSpaceAssignment resolve(Set<Location> locations, SpecifierContext ctxt) {
    AddressGroup addressGroup =
        ctxt.getReferenceBook(_bookName)
            .orElseThrow(
                () -> new NoSuchElementException("ReferenceBook '" + _bookName + "' not found"))
            .getAddressGroup(_addressGroupName)
            .orElseThrow(
                () -> new NoSuchElementException("AddressGroup '" + _addressGroupName + "' found"));

    return IpSpaceAssignment.builder()
        .assign(
            locations,
            AclIpSpace.union(
                addressGroup
                    .getAddresses()
                    .stream()
                    .map(add -> new IpWildcard(add).toIpSpace())
                    .collect(Collectors.toList())))
        .build();
  }
}

@@ -25,16 +25,80 @@
 ifier;%0A%0A
+import static com.google.common.base.MoreObjects.firstNonNull;%0A%0A
 import j
@@ -255,16 +255,59 @@
 pSpace;%0A
+import org.batfish.datamodel.EmptyIpSpace;%0A
 import o
@@ -1865,16 +1865,46 @@
 ations,%0A
+            firstNonNull(%0A    
         
@@ -1925,16 +1925,20 @@
 .union(%0A
+    
         
@@ -1970,32 +1970,36 @@
                 
+    
 .getAddresses()%0A
@@ -2018,16 +2018,20 @@
         
+    
 .stream(
@@ -2052,16 +2052,20 @@
         
+   
+ 
 .map(add
@@ -2121,16 +2121,20 @@
         
+    
 .collect
@@ -2155,16 +2155,56 @@
 List()))
+,%0A                EmptyIpSpace.INSTANCE)
 )%0A      

fix NPE