
from autobahn.twisted.resource import WebSocketResource, \
                                      WSGIRootResource, \
                                      HTTPChannelHixie76Aware


from twisted.application import service, internet, strports
from twisted.internet import reactor
from twisted.python.threadpool import ThreadPool
from twisted.web import server, resource
from twisted.web.wsgi import WSGIResource
from twisted.web.static import Data, File

import config
from oscserver import OSCServerProtocol
from websockets import BroadcastServerFactory, AnotationServerFactory
from webapp import app


WEB_PORT = 8080
WS_PORT = 8090
OSC_PORT = 9090

class BaseRedirect(resource.Resource):
    isLeaf = True
    def render_GET(self, request):
        request.redirect(request.URLPath().child('p/'))
        return ""

def make_service(conn, debug=False):

    s = service.MultiService()
    # Create and start a thread pool,
    wsgiThreadPool = ThreadPool()
    wsgiThreadPool.start()

    # ensuring that it will be stopped when the reactor shuts down
    reactor.addSystemEventTrigger('after', 'shutdown', wsgiThreadPool.stop)


    wsFactory = BroadcastServerFactory("ws://localhost:%d/broadcast" % getattr(config,'WS_PORT',WS_PORT),
                                       debug = debug,
                                       debugCodePaths = debug)
    wsFactory.setProtocolOptions(allowHixie76 = True)
    wsResource = WebSocketResource(wsFactory)


    wsAnnotFactory = AnotationServerFactory("ws://localhost:%d/annot" % getattr(config,'WS_PORT',WS_PORT),
                                       debug = debug,
                                       debugCodePaths = debug,
                                       ws_factory = wsFactory,
                                       conn = conn)
    wsAnnotFactory.setProtocolOptions(allowHixie76 = True)
    wsAnnotResource = WebSocketResource(wsAnnotFactory)


    rootWs = Data("", "text/plain")

    rootWs.putChild("broadcast", wsResource)
    rootWs.putChild("annot", wsAnnotResource)

    webResource = resource.Resource()
    webResource.putChild("",BaseRedirect())
    webResource.putChild(getattr(config,'STATIC_URL').lstrip('/'), File(getattr(config,'STATIC_ROOT')))
    # Create the WSGI resource
    wsgiAppAsResource = WSGIResource(reactor, wsgiThreadPool, app)
    webResource.putChild('p', wsgiAppAsResource)


    # Hooks for twistd

    webserver = strports.service('tcp:%d' % getattr(config,'WEB_PORT',WEB_PORT), server.Site(webResource))
    webserver.setServiceParent(s)

    wsserver = strports.service('tcp:%d' % getattr(config,'WS_PORT',WS_PORT), server.Site(rootWs))
    wsserver.setServiceParent(s)

    oscservice = internet.UDPServer(getattr(config,'OSC_PORT',OSC_PORT), OSCServerProtocol(wsFactory, conn))
    oscservice.setServiceParent(s)

    return s
