package io.teknek.nibiru.coordinator;

import io.teknek.nibiru.Consistency;
import io.teknek.nibiru.ConsistencyLevel;
import io.teknek.nibiru.Destination;
import io.teknek.nibiru.Token;
import io.teknek.nibiru.transport.Message;
import io.teknek.nibiru.transport.Response;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class EventualCoordinator {

  private ExecutorService executor;
  
  public EventualCoordinator(){
    
  }

  public Response handleMessage(Token token, Message message, List<Destination> destinations,
          long timeoutInMs, Consistency consistency, Destination destinationLocal, LocalAction action) {
    if (destinations.size() == 1 && destinations.contains(destinationLocal)) {
      return action.handleReqest();
    }
    boolean alreadyRerouted = false;
    if (message.getPayload().containsKey("reroute")){
      alreadyRerouted = true;
      return action.handleReqest();
    }

    
    Consistency c = null;
    if (consistency == null) {
      c = new Consistency().withLevel(ConsistencyLevel.N).withParameter("n", 1);
    }

    if (c.getLevel() == ConsistencyLevel.ALL) {
      List<Callable<Response>> calls = new ArrayList<Callable<Response>>();
      for (Destination destination : destinations) {
        // id destination is
      }
    }

    return null;
  }

  public void init(){
    executor = Executors.newFixedThreadPool(1024);
  }
  
  public void shutdown(){
    executor.shutdown();
  }
}

@@ -734,16 +734,22 @@
 onLocal,
+ final
  LocalAc
@@ -759,24 +759,129 @@
 n action) %7B%0A
+    if (destinations.size() == 0 )%7B%0A      throw new RuntimeException(%22No place to route message%22);%0A    %7D%0A
     if (dest
@@ -997,40 +997,110 @@
     
-boolean alreadyRerouted = false;
+//TODO if the message is routed here but here is not the correct place%0A    // we should route it again
 %0A   
@@ -1154,38 +1154,8 @@
 ))%7B%0A
-      alreadyRerouted = true;%0A
     
@@ -1191,21 +1191,16 @@
 );%0A    %7D
-%0A%0A   
  %0A    Co
@@ -1527,28 +1527,321 @@
     
-// id destination is
+if (destination.equals(destinationLocal))%7B%0A          calls.add(%0A                  new Callable%3CResponse%3E()%7B%0A                    public Response call() throws Exception %7B%0A                      return action.handleReqest();%0A                    %7D%7D%0A                  );          %0A        %7D else %7B%0A          %0A        %7D
 %0A   

Handle o matching endpoints