class RuntimeBackendInit(webapp2.RequestHandler):
    
    # contains a list of all connected ClawUser objects      
    allUsersList = []
    
    def get(self):
             
        self.__getConnectedUsers()
        self.__setupSecureChannel()
        self.__setupClientChannel()
        
        # set shutdown hook
        runtime.set_shutdown_hook(self.isShuttingDown)

    def __setupSecureChannel(self):
        self.secureChannel = PubnubChanListenerFactory(
                                         gl.PUBLISH_KEY_CLAW_APP_SECURE, 
                                         gl.SUBSCRIBE_KEY_CLAW_APP_SECURE, 
                                         gl.SECRET_KEY_CLAW_APP_SECURE, 
                                         True, 
                                         'ClawComm', 
                                         self.secureCommCallback
                                         )
        
    def __setupClientChannel(self):
        self.publishClient = Pubnub(gl.PUBLISH_KEY_PUBLIC, gl.SUBSCRIBE_KEY_PUBLIC, gl.SECRET_KEY_PUBLIC, False)
        
    def __getConnectedUsers(self):
        # Get existing claw users
        # Query
        self.allUsers = ClawUser().all()
        self.allUsers.order("-timestamp")            
        self.allUsersList = self.allUsers.fetch(limit=gl.MAX_CONNECTIONS)
    
    
    def __updateConnectedUsers(self):
        for user in self.allUsersList:
            print user.channel
            
    
    def isShuttingDown(self):
#         logging.info('shutdown hook called, trying to kill BackgroundThread---------')
        
        self.secureChannel.destroy()
        return True
    
    def secureCommCallback(self, message):
        logging.info(message['text'])
        return True
    
    
    def testBlocking(self):
        while True:
            logging.info(self, 'instance still alive')
            time.sleep(2)
 def get(self):
                     
     allUsers = ClawUser().all()
     numusers = allUsers.count() #max 1000, not an issue in our case
     
     if numusers < gl.MAX_CONNECTIONS:
         
         hasher = hashlib.sha1()
         hasher.update(str(time.time()))
         channelid = hasher.hexdigest()[:20]
         timestamp = datetime.now()
     
         cu = ClawUser()
         cu.channel = channelid
         cu.timestamp = timestamp
         cu.put() # may need TransactionFailedError handling later
         
         j2_env = Environment(loader=FileSystemLoader('template'),
                      trim_blocks=True)
         
         templateVars = { 
                         "title" :           "Claw Controller Client",
                         "channel" :         channelid,
                         "timestamp" :       timestamp,
                         "sub" :             gl.SUBSCRIBE_KEY_PUBLIC,
                         "pub" :             gl.PUBLISH_KEY_PUBLIC,
                         "ssl" :             'false',
                         "queuepos" :             numusers
            }
         
         self.response.out.write( j2_env.get_template('in_queue2.html').render(templateVars) )
         
     else:
         # replace with jenga template later probably
         self.response.out.write("<html><body>")
         self.response.out.write("<p>Too many queued users, please retry laters</p>")
         self.response.out.write("</body></html>")
 def __getConnectedUsers(self):
     # Get existing claw users
     # Query
     self.allUsers = ClawUser().all()
     self.allUsers.order("-timestamp")            
     self.allUsersList = self.allUsers.fetch(limit=gl.MAX_CONNECTIONS)