package org.opennms.netmgt.dao.support;

import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

import org.opennms.core.utils.LazyList;
import org.opennms.netmgt.dao.api.ResourceDao;
import org.opennms.netmgt.model.OnmsResource;
import org.opennms.netmgt.model.OnmsResourceType;

import com.google.common.base.Preconditions;
import com.google.common.collect.Lists;

public class LazyChildResourceLoader implements LazyList.Loader<OnmsResource> {
    private final ResourceDao m_resourceDao;
    private OnmsResource m_parent;

    public LazyChildResourceLoader(ResourceDao resourceDao) {
        m_resourceDao = resourceDao;
    }

    public void setParent(OnmsResource parent) {
        m_parent = parent;
    }

    @Override
    public List<OnmsResource> load() {
        Preconditions.checkNotNull(m_parent, "parent attribute");
        final List<OnmsResource> children = Lists.newLinkedList();
        for (OnmsResourceType resourceType : getAvailableResourceTypes()) {
            for (OnmsResource resource : resourceType.getResourcesForParent(m_parent)) {
                resource.setParent(m_parent);
                children.add(resource);
            }
        }
        return children;
    }

    private Collection<OnmsResourceType> getAvailableResourceTypes() {
        return m_resourceDao.getResourceTypes().stream()
                .filter(t -> t.isResourceTypeOnParent(m_parent))
                .collect(Collectors.toList());
    }

}

@@ -355,48 +355,8 @@
 ons;
-%0Aimport com.google.common.collect.Lists;
 %0A%0Apu
@@ -834,66 +834,122 @@
     
-final List%3COnmsResource%3E children = Lists.newLinkedList();
+// Gather the lists of children from all the available resource types and merge them%0A        // into a single list
 %0A   
@@ -945,37 +945,37 @@
 le list%0A        
-for (
+List%3C
 OnmsResourceType
@@ -974,27 +974,20 @@
 urce
-Type resourceType :
+%3E children =
  get
@@ -1014,65 +1014,53 @@
 es()
-) %7B%0A            for (OnmsResource resource : resourceType
+.parallelStream()%0A                .map(t -%3E t
 .get
@@ -1088,18 +1088,16 @@
 parent))
- %7B
 %0A       
@@ -1109,86 +1109,92 @@
     
-resource.setParent(m_parent);%0A                children.add(resource
+.flatMap(rs -%3E rs.stream())%0A                .collect(Collectors.toList()
 );%0A
+%0A
         
     
@@ -1193,23 +1193,118 @@
     
-    %7D%0A        %7D
+// Set the parent field on all of the resources%0A        children.stream().forEach(c -%3E c.setParent(m_parent));
 %0A   
@@ -1451,17 +1451,25 @@
 Types().
-s
+parallelS
 tream()%0A
@@ -1580,17 +1580,16 @@
 ist());%0A
+
     %7D%0A
-%0A
 %7D%0A

Load child resources in parallel.