"""
Benchmark sandbox message processing round trip.
"""

import sys
import time

from twisted.internet import reactor
from twisted.internet.defer import inlineCallbacks, DeferredQueue
from twisted.python import log

from vumi.application.sandbox import JsSandbox
from vumi.transports.base import Transport
from vumi.service import WorkerCreator
from vumi.servicemaker import VumiOptions


class BenchTransport(Transport):

    WORKER_QUEUE = DeferredQueue()

    @inlineCallbacks
    def startWorker(self):
        yield Transport.startWorker(self)
        self.WORKER_QUEUE.put(self)


class BenchApp(JsSandbox):

    WORKER_QUEUE = DeferredQueue()

    @inlineCallbacks
    def startWorker(self):
        yield JsSandbox.startWorker(self)
        self.WORKER_QUEUE.put(self)

    def sandbox_id_for_message(self, msg_or_event):
        return "DUMMY_SANDBOX_ID"


@inlineCallbacks
def run_bench(loops=100):
    opts = VumiOptions()
    opts.postOptions()
    worker_creator = WorkerCreator(opts.vumi_options)

    app = worker_creator.create_worker_by_class(BenchApp, {
        "transport_name": "dummy",
        "javascript": "",
    })

    transport = worker_creator.create_worker_by_class(BenchTransport, {
        "transport_name": "dummy",
    })

    yield transport.startService()
    print "Waiting for transport ..."
    yield BenchTransport.WORKER_QUEUE.get()

    yield app.startService()
    print "Waiting for worker ..."
    yield BenchApp.WORKER_QUEUE.get()

    start = time.time()
    for i in range(loops):
        transport.publish_message(
            content="Hi!",
            to_addr="+1234",
            from_addr="+5678",
            transport_type="ussd",
        )
        # TODO: wait for message

    elapsed = time.time() - start
    print elapsed

    yield transport.stopService()
    yield app.stopService()


if __name__ == "__main__":
    log.startLogging(sys.stdout)
    reactor.callLater(0, run_bench, loops=100)
    reactor.run()

@@ -556,37 +556,163 @@
    self.
-WORKER_QUEUE.put(self
+message_queue = DeferredQueue()%0A        self.WORKER_QUEUE.put(self)%0A%0A    def handle_outbound_message(self, msg):%0A        self.message_queue.put(msg
 )%0A%0A%0Aclas
@@ -1251,16 +1251,397 @@
 ipt%22: %22%22
+%22%0A            api.on_inbound_message = function(command) %7B%0A                this.request('outbound.reply', %7Bcontent: 'reply'%7D,%0A                function (reply) %7B%0A                    this.done();%0A                %7D);%0A            %7D;%0A        %22%22%22,%0A        %22sandbox%22: %7B%0A            'outbound': %7B%0A                'cls': 'vumi.application.sandbox.OutboundResource',%0A            %7D,%0A        %7D
 ,%0A    %7D)
@@ -2208,32 +2208,71 @@
     
-# TODO: wait for message
+reply = yield transport.message_queue.get()%0A        print reply
 %0A%0A  

Add replies from sandbox.