"""	Classes that load a set of modules using python entry points. """

from pkg_resources import iter_entry_points

from aleph.utils.log import getlog

class EntryPointLoader (dict):
	def __init__ (self, group, log=None):
		self.log = log or getlog(self)
		self.group = group
		self.entry_points = {ep.name: ep for ep in iter_entry_points(group=self.group)}
	
	def load (self, *names):
		"""	Load the given entry points """
		for name in names:
			self.load_entry_point(name)
	
	def load_entry_point (self, name):
		""" Load a given entry point """
		try:
			if name in self:
				return self[name]
			obj = self.entry_points[name].load()
			# Set the objects __name__ if it does not have one
			if not hasattr(obj, '__name__'):
				obj.__name__ = name
		except ImportError:
			self.log.error("Failed to import %s from %s", name, self.group)
			raise
		except KeyError:
			self.log.error("Could not find %s from %s", name, self.group)
			raise
		self.log.debug("Loaded %s from %s", name, self.group)
		self[name] = obj
		return self[name]
