from twisted.web.client import Agent
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
import os
import sys
import routeconf


class Melvil(Resource):
    '''
    The Twisted resource representing a set of redirects. This
    includes a RouteList object, which represents a set of possible
    routes.
    '''
    isLeaf = True

    def __init__(self, routes, agent):
        Resource.__init__(self)
        self.routes = routes
        self.agent = agent

    def render_GET(self, request):
        routeconf.domain_for(request)
        return self.routes.handle(request, self.agent)

    @staticmethod
    def run_melvil():
        '''
        Run a Melvil instance.
        '''
        if len(sys.argv) > 1:
            conf_dir = sys.argv[1]
        else:
            conf_dir = os.getenv('MELVIL_DIR', os.getcwd())
        port = int(os.getenv('PORT', 8080))

        routes = routeconf.load_routes(conf_dir)
        agent = Agent(reactor)
        sys.stderr.write(routes.pretty())
        reactor.listenTCP(port, Site(Melvil(routes, agent)))
        reactor.run()

if __name__ == '__main__':
    Melvil.run_melvil()
