class Client(ApplicationSession):
    '''
    Client is used to connect to the router
    all Helpers should connect to the router
    since some directives are being passed through
    PUB/SUB topics.
    Moreover, the Client obtains or create a new
    node id to use later. The id is also used by the
    adapter. using a unified id an ovs helper can find
    which adapter it corresponds to amongst the running
    adapters
    '''
    def __init__(self, config):
        ApplicationSession.__init__(self, config)
        self.cluster_state = ClusterState(self)
        try:
            self.node_id = (open('/cygnus/node', 'r')).read()
        except IOError:
            self.node_id = str(uuid.uuid1())
            f = open('/cygnus/node', 'w')
            f.write(self.node_id)
            f.close()

    @inlineCallbacks
    def onJoin(self, details):

        print("Helper Attached to Router")
        self.cluster_state.init()
        yield self.subscribe(self.cluster_state)

    def leave(self, reason=None, log_message=None):
        ApplicationSession.leave(self, reason, log_message)

    def disconnect(self):
        ApplicationSession.disconnect(self)
 def __init__(self, config):
     ApplicationSession.__init__(self, config)
     self.cluster_state = ClusterState(self)
     try:
         self.node_id = (open('/cygnus/node', 'r')).read()
     except IOError:
         self.node_id = str(uuid.uuid1())
         f = open('/cygnus/node', 'w')
         f.write(self.node_id)
         f.close()
 def __init__(self, setup):
     resource.Resource.__init__(self)
     self.setup = setup
     self.cluster_state = ClusterState(None)
class NetworkDriver(resource.Resource):
    isLeaf = True

    def __init__(self, setup):
        resource.Resource.__init__(self)
        self.setup = setup
        self.cluster_state = ClusterState(None)
    def render_POST(self, request):
        op = request.uri.decode('utf-8')[len('/NetworkDriver.'):]
        print(request.uri)
        print(op)
        return {
                'GetCapabilities': self.getCapabilities,
                'CreateNetwork': self.createNetwork,
                'DeleteNetwork': self.deleteNetwork,
                'CreateEndpoint': self.createEndpoint,
                'DeleteEndpoint': self.deleteEndpoint,
                'Join': self.join,
                'EndpointOperInfo': self.endpointInfo
                }.get(op)(request)

    def getCapabilities(self, request):
        # GetCapabilities expects no request payload
        payload = {
                    "Scope":"local"
                    }
        response = json.dumps(payload).encode('utf-8')
        request.write(response)
        request.finish()
        return server.NOT_DONE_YET

    def createNetwork(self, request):
        payload = {}
        specs = request.content.read().decode('utf-8')
        specs = json.loads(specs)
        print(specs)
        print("DONEEEE!!")
        network = Network(specs['NetworkID'], specs['IPv4Data'][0])
        try:
            self.cluster_state.addInterface(network_id, specs['IPv4Data'][0])
        except Exception as e:
            error = str(e)
            payload = {"Err":error}
        response = json.dumps(payload).encode('utf-8')
        request.write(response)
        request.finish()
        return server.NOT_DONE_YET

    def deleteNetwork(self, request):
        payload = {}
        body = request.content.read().decode('utf-8')
        body = json.loads(body)
        print(body)
        network_id = body["NetworkID"]
        try:
            self.cluster_state.removeInterface(network_id)
        except Exception as e:
            error = str(e)
            payload = {"Err":error}
        response = json.dumps(payload).encode('utf-8')
        request.write(response)
        request.finish()
        return server.NOT_DONE_YET

    def createEndpoint(self, request):
        payload = {}
        specs = request.content.read().decode('utf-8')
        specs = json.loads(specs)
        network_id = specs["NetworkID"]
        try:
            assert 1==2
        except Exception as e:
            error = str(e)
            payload= {"Err": error}
            raise e
        response = json.dumps(payload).encode('utf-8')
        request.write(response)
        request.finish()
        return server.NOT_DONE_YET

    def deleteEndpoint(self, request):
        payload = {}
        response = json.dumps(payload).encode('utf-8')
        request.write(response)
        request.finish()
        return server.NOT_DONE_YET

    def join(self, request):
        payload = {}
        print(request.content.read().decode('utf-8'))
        response = json.dumps(payload).encode('utf-8')
        request.write(response)
        request.finish()
        return server.NOT_DONE_YET

    def endpointInfo(self, request):
        payload = {'Value':{}}
        print(request.content.read().decode('utf-8'))
        response = json.dumps(payload).encode('utf-8')
        request.write(response)
        request.finish()
        return server.NOT_DONE_YET