# -*- test-case-name: vumi.middleware.tests.test_base -*-

from twisted.internet.defer import inlineCallbacks, returnValue


class BaseMiddleware(object):
    """Common middleware base class.

    This is a convenient repository for commonalities between the various
    middlewares. You should not subclass or instantiate this directly.
    """

    def __init__(self, worker, config):
        self.worker = worker
        self.config = config

    def setup_middleware(self):
        pass

    def handle_inbound(self, message, endpoint_name):
        return message

    def handle_outbound(self, message, endpoint_name):
        return message

    def handle_event(self, message, endpoint_name):
        return message

    def handle_failure(self, message, endpoint_name):
        return message


class TransportMiddleware(BaseMiddleware):
    """Message processor middleware for Transports.
    """


class ApplicationMiddleware(BaseMiddleware):
    """Message processor middleware for Applications.
    """


class MiddlewareStack(object):
    """Ordered list of middlewares to pass a Message through.
    """

    def __init__(self, middlewares):
        self.middlewares = middlewares

    @inlineCallbacks
    def _handle(self, middlewares, handler_name, message, endpoint_name):
        method_name = 'handle_%s' % (handler_name,)
        for middleware in middlewares:
            handler = getattr(middleware, method_name)
            message = yield handler(message, endpoint_name)
        returnValue(message)

    def apply_consume(self, handler_name, message, endpoint_name):
        return self._handle(
            self.middlewares, handler_name, message, endpoint_name)

    def apply_publish(self, handler_name, message, endpoint_name):
        return self._handle(
            reversed(self.middlewares), handler_name, message, endpoint_name)

@@ -117,16 +117,97 @@
 nValue%0A%0A
+from vumi.utils import load_class_by_string%0Afrom vumi.errors import ConfigError%0A%0A
 %0Aclass B
@@ -1271,16 +1271,802 @@
 ewares%0A%0A
+    @staticmethod%0A    def middlewares_from_config(worker, config):%0A        %22%22%22Return a list of middleware objects created from a worker%0A           configuration.%0A           %22%22%22%0A        middlewares = %5B%5D%0A        for item in config.get(%22middleware%22, %5B%5D):%0A            if not %22name%22 in item:%0A                raise ConfigError(%22Middleware items must specify a name.%22)%0A            middleware_name = item%5B%22name%22%5D%0A            middleware_config = config.get(middleware_name)%0A            if not %22cls%22 in item:%0A                raise ConfigError(%22Middleware items must specify a class.%22)%0A            cls_name = item%5B%22cls%22%5D%0A            cls = load_class_by_string(cls_name)%0A            middleware = cls(worker, middleware_config)%0A            middlewares.append(middleware)%0A        return middlewares%0A%0A
     @inl

Add middlewares_from_config method.