#!/usr/bin/env python
""" bank10: Several Counters with individual queues"""
from SimPy.Simulation  import *
from random import expovariate,seed

class Source(Process):
    """ Source generates customers randomly"""

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

def NoInSystem(R):                                   
    """ The number of customers in the resource R
    in waitQ and active Q"""
    return (len(R.waitQ)+len(R.activeQ))             

class Customer(Process):
    """ Customer arrives, is served and leaves """
        
    def visit(self,timeInBank=0):       
        arrive=now()
        Qlength = [NoInSystem(counter[i]) for i in range(Nc)]              
        print "%7.4f %s: Here I am. %s   "%(now(),self.name,Qlength)       
        for i in range(Nc):                                                
            if Qlength[i] ==0 or Qlength[i]==min(Qlength):
                join =i ; break                                            

        yield request,self,counter[join]
        wait=now()-arrive
        print "%7.4f %s: Waited %6.3f"%(now(),self.name,wait)
        tib = expovariate(1.0/timeInBank)
        yield hold,self,tib
        yield release,self,counter[join]

        print "%7.4f %s: Finished    "%(now(),self.name)

def model(theseed):
    global Nc,counter
    seed(theseed)
    Nc = 2
    counter = [Resource(name="Clerk0"),Resource(name="Clerk1")]

    initialize()    
    source = Source('Source')
    activate(source,source.generate(number=5,interval=10.0),0.0)
    simulate(until=400.0)

model(theseed = 3939393)
