from paste.deploy import loadapp

from twisted.internet import reactor
from twisted.python.threadpool import ThreadPool
from twisted.web.server import Site
from twisted.web.wsgi import WSGIResource


def add_site(config_func, ini_path="app.ini", relative_to="."):
    # Create and start a thread pool,
    pool = ThreadPool()
    pool.start()
    # ensuring that it will be stopped when the reactor shuts down
    reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
    # init site
    app = loadapp("config:" + ini_path, relative_to=relative_to)
    resource = WSGIResource(reactor, pool, app)
    site = Site(resource)
    port = config_func("port", default=8080, _type=int)
    # just listen
    try:
        reactor.listenTCP(port, site)
    except Exception, e:
        reactor.stop()
