#!/usr/bin/env python
""" bank09: Simulate customers arriving
    at random, using a Source requesting service
    from several clerks but a single queue
    with a random servicetime
"""
from __future__ import generators
from SimPy.Simulation  import *
from random import Random

class Source(Process):
    """ Source generates customers randomly"""
    def __init__(self,seed=333):
        Process.__init__(self)
        self.SEED = seed

    def generate(self,number,interval):       
        rv = Random(self.SEED)
        for i in range(number):
            c = Customer(name = "Customer%02d"%(i,))
            activate(c,c.visit(timeInBank=12.0))
            t = rv.expovariate(1.0/interval)
            yield hold,self,t

class Customer(Process):
    """ Customer arrives, is served and leaves """
    def __init__(self,name):
        Process.__init__(self)
        self.name = name
        
    def visit(self,timeInBank=0):       
        arrive=now()
        print "%7.4f %s: Here I am "%(now(),self.name)
        yield request,self,counter
        wait=now()-arrive
        print "%7.4f %s: Waited %6.3f"%(now(),self.name,wait)
        tib = counterRV.expovariate(1.0/timeInBank)
        yield hold,self,tib
        yield release,self,counter
        print "%7.4f %s: Finished"%(now(),self.name)

def model(counterseed=393939):
    global counter,counterRV
    counter = Resource(name="Clerk",capacity = 2)        
    counterRV = Random(counterseed)
    initialize()
    sourceseed = 99999
    source = Source(seed = sourceseed)
    activate(source,source.generate(5,10.0),0.0)
    simulate(until=400.0)

model()
