from constants import *
import collections
import uuid

class CallBuffer():
    def __init__(self):
        self.waiters = set()
        self.cache = collections.deque(maxlen=CALL_CACHE_MAX)
        self.call_waiters = {}

    def wait_for_calls(self, callback, cursor=None):
        if cursor:
            calls = []
            cursor_found = False
            for call in self.cache:
                if call['id'] == cursor:
                    cursor_found = True
                    continue
                if not cursor_found:
                    continue
                calls.append(call)
            if calls:
                callback(calls)
                return
        self.waiters.add(callback)

    def return_call(self, id, response):
        callback = self.call_waiters.pop(id, None)
        if callback:
            callback(response)

    def create_call(self, command, args, callback=None):
        call_id = uuid.uuid4().hex
        call = {
            'id': call_id,
            'command': command,
            'args': args,
        }

        if callback:
            self.call_waiters[call_id] = callback
        self.cache.append(call)

        for callback in self.waiters:
            callback([call])
        self.waiters = set()

@@ -273,31 +273,8 @@
 e):%0A
-        if cursor:%0A    
     
@@ -288,20 +288,16 @@
 ls = %5B%5D%0A
-    
         
@@ -316,21 +316,37 @@
  = False
-%0A    
+ if cursor else True%0A
         
@@ -377,28 +377,24 @@
             
-    
 if call%5B'id'
@@ -418,28 +418,24 @@
             
-  
-  
 cursor_found
@@ -450,36 +450,32 @@
                 
-    
 continue%0A       
@@ -459,36 +459,32 @@
        continue%0A
-    
             if n
@@ -508,36 +508,32 @@
                 
-    
 continue%0A       
@@ -517,36 +517,32 @@
        continue%0A
-    
             call
@@ -560,28 +560,24 @@
 ll)%0A        
-  
-  
 if calls:%0A  
@@ -574,20 +574,16 @@
  calls:%0A
-    
         
@@ -602,20 +602,16 @@
 (calls)%0A
-    
         

Change call buffer