package stroom.node.client;

import stroom.dispatch.client.Rest;
import stroom.dispatch.client.RestFactory;
import stroom.node.shared.NodeResource;

import com.google.gwt.core.client.GWT;

import java.util.List;
import java.util.function.Consumer;
import javax.inject.Inject;
import javax.inject.Singleton;

@Singleton
public class NodeCache {

    private static final NodeResource NODE_RESOURCE = GWT.create(NodeResource.class);

    private final RestFactory restFactory;

    private List<String> nodeNames;
    private List<String> enabledNodeNames;

    @Inject
    NodeCache(final RestFactory restFactory) {
        this.restFactory = restFactory;
    }

    public void listAllNodes(final Consumer<List<String>> nodeListConsumer,
                             final Consumer<Throwable> throwableConsumer) {
        if (nodeNames == null) {
            final Rest<List<String>> rest = restFactory.create();
            rest.onSuccess(nodeNames -> {
                // Store node list for future queries.
                this.nodeNames = nodeNames;
                nodeListConsumer.accept(nodeNames);
            }).onFailure(throwableConsumer).call(NODE_RESOURCE).listAllNodes();
        } else {
            nodeListConsumer.accept(nodeNames);
        }
    }

    public void listEnabledNodes(final Consumer<List<String>> nodeListConsumer,
                                 final Consumer<Throwable> throwableConsumer) {
        if (enabledNodeNames == null) {
            final Rest<List<String>> rest = restFactory.create();
            rest.onSuccess(nodeNames -> {
                // Store node list for future queries.
                this.enabledNodeNames = nodeNames;
                nodeListConsumer.accept(nodeNames);
            }).onFailure(throwableConsumer).call(NODE_RESOURCE).listEnabledNodes();
        } else {
            nodeListConsumer.accept(enabledNodeNames);
        }
    }
}

@@ -914,32 +914,53 @@
             rest
+%0A                    
 .onSuccess(nodeN
@@ -961,32 +961,40 @@
 (nodeNames -%3E %7B%0A
+        
                 
@@ -1044,24 +1044,32 @@
             
+        
 this.nodeNam
@@ -1076,32 +1076,40 @@
 es = nodeNames;%0A
+        
                 
@@ -1160,59 +1160,130 @@
     
-%7D).onFailure(throwableConsumer).call(NODE_RESOURCE)
+        %7D)%0A                    .onFailure(throwableConsumer)%0A                    .call(NODE_RESOURCE)%0A                    
 .lis
@@ -1659,16 +1659,37 @@
     rest
+%0A                    
 .onSucce
@@ -1698,32 +1698,40 @@
 (nodeNames -%3E %7B%0A
+        
                 
@@ -1781,24 +1781,32 @@
             
+        
 this.enabled
@@ -1836,32 +1836,40 @@
                 
+       
+ 
 nodeListConsumer
@@ -1904,59 +1904,130 @@
     
-%7D).onFailure(throwableConsumer).call(NODE_RESOURCE)
+        %7D)%0A                    .onFailure(throwableConsumer)%0A                    .call(NODE_RESOURCE)%0A                    
 .lis

Format code