import re

from hbkif.controllers.status import StatusController
from hbkif.controllers.version import VersionController

class Delegator(object):

    def __init__(self):
        pass

    def __call__(self, environ, start_response):
        path = environ['PATH_INFO']

        if re.match('^/status(/)?$', path):
            # Authenticate user
            controller = StatusController(environ)
            status, headers, body = controller.generate_response()
        elif re.match('^/version(/)?$', path):
           # All bookmarks page
           controller = VersionController(environ)
           status, headers, body = controller.generate_response()
        else:
            # User supplied an invalid URL
            status = '200 OK'
            body = 'hbkif is working!\n\nInvalid URL "{:s}"'.format(environ['PATH_INFO'])
            body = body.encode()
            headers = [('Content-Type', 'text/plain'),
                       ('Content-Length', str(len(body)))]

        # Send the status and response headers to the server
        start_response(status, headers)
        # Return the response body. (Notice it is wrapped in a list although it
        # could be any iterable.)
        return [body]
        

# Set the callable object
application = Delegator()
