import ampoule
import ampoule.util
from twisted.internet import reactor,defer
from twisted.protocols import amp

class Test(amp.Command):
    arguments = [('analysis', amp.String())]
    response = [("result", amp.String())]

class Worker(ampoule.child.AMPChild):
    def analyze(self, analysis):
        return {"result":analysis*4073}
    Test.responder(analyze)

@ampoule.util.mainpoint
def main(args):
    init()
    reactor.run()

@defer.inlineCallbacks
def init():
    p = ampoule.pool.ProcessPool(Worker,min=1,max=4)
    yield p.start()
    defers = []
    for i in range(5):
        d = p.doWork(Test, analysis=str(i))
        d.addCallback(printResult)
        d.addErrback(printErr)
        defers.append(d)
    defer.DeferredList(defers).addCallback(stop)

def printResult(result):
    if isinstance(result, dict):
        print len(result.get("result",""))
    else:
        pass

def printErr(fail):
    print fail

def stop(e):
    print e
    reactor.stop()


if __name__ == "__main__":
    pass
    #init()
    #reactor.run()
