# from threading import RLock
from MetadataService.ProducerConsumer import Producer
from MetadataService.Component import Component
from VolumeExpert import _VolumeExpert
from VolumeCrawler import VolumeCrawler
from InfospaceObjects import Volume

class VolumeCrawlerManager(Component,Producer):

# 	lock = RLock()
	crawler_list = {}
	
	def __init__(self,expert):
		#Contract
		assert isinstance(expert,_VolumeExpert)
		
		Component.__init__(self,public_interface=None) #no interface for this one, dude
		self.set_component_name("FilesystemAgent.VolumeCrawlerManager")

		Producer.__init__(self,5) # FIXME make queue size configurable
		self.expert = expert

	def get_crawler(self,volume):
		assert isinstance(volume,Volume)
# 		self.lock.acquire()
		try: c = self.crawler_list[volume]
		except KeyError: c = self.__start_crawler(volume)
# 		self.lock.release()
		return c
	
	def kill_crawler(self,volume):
		assert isinstance(volume,Volume)
# 		self.lock.acquire()
		self.crawler_list[volume].kill()
		del(self.crawler_list[volume])
# 		self.lock.release()
		
	def kill_all_crawlers(self):
# 		self.lock.acquire()
		crawlers = self.crawler_list.values()
		for a in crawlers:
			self.log.debug("Killing crawler %s",a)
			a.kill()
			self.log.debug("Killed crawler %s",a)
			
		self.log.debug("Killed all crawlers")
		self.crawler_list = {}
# 		self.lock.release()
	
	def __start_crawler(self,volume):
# 		self.lock.acquire()
		self.crawler_list[volume] = VolumeCrawler(volume=volume,
					produce_method=self.produce,expert=self.expert)
					# hack to make the volume crawlers produce through the volume crawler manager
		self.crawler_list[volume].start()
		a = self.crawler_list[volume]
# 		self.lock.release()
		return a
		
	def get_crawlers(self):
# 		self.lock.acquire()
		v = self.crawler_list.values()
# 		self.lock.release()
		return v
