# Path: mcloud/ssl.py
# def listen_ssl(port, resource, interface):
# 
#     settings = inject.instance('settings')
# 
#     from OpenSSL import SSL
# 
#     from twisted.internet import ssl
# 
#     myContextFactory = ssl.DefaultOpenSSLContextFactory(
#         settings.ssl.key, settings.ssl.cert, sslmethod=SSL.SSLv23_METHOD
#     )
#     ctx = myContextFactory.getContext()
# 
#     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_CLIENT_ONCE | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verifyCallback)
#     ctx.set_session_cache_mode(SSL.SESS_CACHE_BOTH)
# 
#     # Since we have self-signed certs we have to explicitly
#     # tell the server to trust them.
# 
#     ctx.load_verify_locations(settings.ssl.ca)
#     ctx.set_session_id(str(datetime.datetime.now()))
# 
#     reactor.listenSSL(port, resource, myContextFactory, interface=interface)
# 
# Path: mcloud/events.py
# class EventBus(object):
#     redis = None
#     protocol = None
# 
#     def __init__(self, redis_connection):
#         super(EventBus, self).__init__()
#         self.redis = redis_connection
# 
#     def fire_event(self, event_name, data=None,  *args, **kwargs):
#         if not data:
#             if kwargs:
#                 data = kwargs
#             elif args:
#                 data = args
# 
#         if not isinstance(data, basestring):
#             data = 'j:' + json.dumps(data)
#         else:
#             data = 'b:' + str(data)
# 
#         return self.redis.publish(event_name, data)
# 
# 
#     def connect(self, host="127.0.0.1", port=6379):
#         log.msg('Event bus connected')
#         d = defer.Deferred()
#         reactor.connectTCP(host, port, EventBusFactory(d, self))
#         return d
# 
#     def on(self, pattern, callback):
#         if not self.protocol:
#             raise Exception('Event bus is not connected yet!')
#         self.protocol.on(pattern, callback)
#         log.msg('Registered %s for channel: %s' % (callback, pattern))
# 
#     def cancel(self, pattern, callback):
#         if not self.protocol:
#             raise Exception('Event bus is not connected yet!')
#         self.protocol.cancel(pattern, callback)
#         log.msg('unRegistered %s for channel: %s' % (callback, pattern))
# 
#     def once(self, pattern, callback):
#         if not self.protocol:
#             raise Exception('Event bus is not connected yet!')
# 
#         def _once_and_remove(*args, **kwargs):
#             self.protocol.cancel(pattern, _once_and_remove)
#             callback(*args, **kwargs)
# 
#         self.protocol.on(pattern, _once_and_remove)
#         log.msg('Registered %s for single invocation on channel: %s' % (callback, pattern))
# 
#     def wait_for_event(self, pattern, timeout=False):
#         d = defer.Deferred()
# 
#         def _on_message(channel, message):
#             if not d.called:
#                 d.callback(message)
# 
#         self.on(pattern, _on_message)
# 
#         if not timeout == 0:
#             return txtimeout(d, timeout, lambda: d.callback(None))
#         else:
#             return d


import json
import os
import sys
import inject
import txredisapi
from autobahn.twisted.resource import WSGIRootResource, WebSocketResource
from mcloud.ssl import listen_ssl
from mcloud.events import EventBus
from twisted.internet import reactor, defer
from twisted.internet.defer import inlineCallbacks, AlreadyCalledError, CancelledError
from autobahn.twisted.websocket import WebSocketServerFactory
from autobahn.twisted.websocket import WebSocketClientFactory
from twisted.python.failure import Failure
from twisted.web.server import Site
from twisted.python import log
from twisted.web.static import File
from pkg_resources import resource_filename
from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketServerProtocol
                from mcloud.ssl import CtxFactory
    from twisted.python import log
        pass

    def onConnect(self, request):
        pass

    def onOpen(self):
        self.factory.server.on_client_connect(self)

    def onClose(self, wasClean, code, reason):
        self.factory.server.on_client_disconnect(self, wasClean, code, reason)

    def onMessage(self, payload, isBinary):
        # log.msg('Websocket server in: %s' % payload)
        # print(self.factory.server.on_message())

        reactor.callLater(0, self.factory.server.on_message, self, payload, isBinary)

    def send_event(self, event_name, data=None):
        data_ = {'type': 'event', 'name': event_name, 'data': data}
        # log.msg('Sent out event: %s' % event_name)
        return self.sendMessage(json.dumps(data_))

    def send_response(self, request_id, response, success=True):
        data_ = {'type': 'response', 'id': request_id, 'success': success, 'response': response}
        # log.msg('Sent out response: %s' % request_id)
        return self.sendMessage(json.dumps(data_))


class Server(object):
    redis = inject.attr(txredisapi.Connection)

# Path: mcloud/ssl.py
# def listen_ssl(port, resource, interface):
# 
#     settings = inject.instance('settings')
# 
#     from OpenSSL import SSL
# 
#     from twisted.internet import ssl
# 
#     myContextFactory = ssl.DefaultOpenSSLContextFactory(
#         settings.ssl.key, settings.ssl.cert, sslmethod=SSL.SSLv23_METHOD
#     )
#     ctx = myContextFactory.getContext()
# 
#     ctx.set_verify(SSL.VERIFY_PEER | SSL.VERIFY_CLIENT_ONCE | SSL.VERIFY_FAIL_IF_NO_PEER_CERT, verifyCallback)
#     ctx.set_session_cache_mode(SSL.SESS_CACHE_BOTH)
# 
#     # Since we have self-signed certs we have to explicitly
#     # tell the server to trust them.
# 
#     ctx.load_verify_locations(settings.ssl.ca)
#     ctx.set_session_id(str(datetime.datetime.now()))
# 
#     reactor.listenSSL(port, resource, myContextFactory, interface=interface)
# 
# Path: mcloud/events.py
# class EventBus(object):
#     redis = None
#     protocol = None
# 
#     def __init__(self, redis_connection):
#         super(EventBus, self).__init__()
#         self.redis = redis_connection
# 
#     def fire_event(self, event_name, data=None,  *args, **kwargs):
#         if not data:
#             if kwargs:
#                 data = kwargs
#             elif args:
#                 data = args
# 
#         if not isinstance(data, basestring):
#             data = 'j:' + json.dumps(data)
#         else:
#             data = 'b:' + str(data)
# 
#         return self.redis.publish(event_name, data)
# 
# 
#     def connect(self, host="127.0.0.1", port=6379):
#         log.msg('Event bus connected')
#         d = defer.Deferred()
#         reactor.connectTCP(host, port, EventBusFactory(d, self))
#         return d
# 
#     def on(self, pattern, callback):
#         if not self.protocol:
#             raise Exception('Event bus is not connected yet!')
#         self.protocol.on(pattern, callback)
#         log.msg('Registered %s for channel: %s' % (callback, pattern))
# 
#     def cancel(self, pattern, callback):
#         if not self.protocol:
#             raise Exception('Event bus is not connected yet!')
#         self.protocol.cancel(pattern, callback)
#         log.msg('unRegistered %s for channel: %s' % (callback, pattern))
# 
#     def once(self, pattern, callback):
#         if not self.protocol:
#             raise Exception('Event bus is not connected yet!')
# 
#         def _once_and_remove(*args, **kwargs):
#             self.protocol.cancel(pattern, _once_and_remove)
#             callback(*args, **kwargs)
# 
#         self.protocol.on(pattern, _once_and_remove)
#         log.msg('Registered %s for single invocation on channel: %s' % (callback, pattern))
# 
#     def wait_for_event(self, pattern, timeout=False):
#         d = defer.Deferred()
# 
#         def _on_message(channel, message):
#             if not d.called:
#                 d.callback(message)
# 
#         self.on(pattern, _on_message)
# 
#         if not timeout == 0:
#             return txtimeout(d, timeout, lambda: d.callback(None))
#         else:
#             return d


# Path: mcloud/remote.py
import json
import os
import sys
import inject
import txredisapi
from autobahn.twisted.resource import WSGIRootResource, WebSocketResource
from mcloud.ssl import listen_ssl
from mcloud.events import EventBus
from twisted.internet import reactor, defer
from twisted.internet.defer import inlineCallbacks, AlreadyCalledError, CancelledError
from autobahn.twisted.websocket import WebSocketServerFactory
from autobahn.twisted.websocket import WebSocketClientFactory
from twisted.python.failure import Failure
from twisted.web.server import Site
from twisted.python import log
from twisted.web.static import File
from pkg_resources import resource_filename
from autobahn.twisted.websocket import WebSocketClientProtocol, WebSocketServerProtocol
                from mcloud.ssl import CtxFactory
    from twisted.python import log

        pass

    def onConnect(self, request):
        pass

    def onOpen(self):
        self.factory.server.on_client_connect(self)

    def onClose(self, wasClean, code, reason):
        self.factory.server.on_client_disconnect(self, wasClean, code, reason)

    def onMessage(self, payload, isBinary):
        # log.msg('Websocket server in: %s' % payload)
        # print(self.factory.server.on_message())

        reactor.callLater(0, self.factory.server.on_message, self, payload, isBinary)

    def send_event(self, event_name, data=None):
        data_ = {'type': 'event', 'name': event_name, 'data': data}
        # log.msg('Sent out event: %s' % event_name)
        return self.sendMessage(json.dumps(data_))

    def send_response(self, request_id, response, success=True):
        data_ = {'type': 'response', 'id': request_id, 'success': success, 'response': response}
        # log.msg('Sent out response: %s' % request_id)
        return self.sendMessage(json.dumps(data_))


class Server(object):
    redis = inject.attr(txredisapi.Connection)

    eb = inject.attr(EventBus)