from debpartial_mirror import Backend


class Controller:
	def __init__(self, configuration, mirrorNames):
		self._mirrors = []
		self._merges = []
		cnf_mirrors, cnf_merges = configuration.get_backends()

		def useBackend(backend):
			if not mirrorNames:
				return True
			return backend.section in mirrorNames

		for b in cnf_mirrors:
			if useBackend(b):
				self._mirrors.append(Backend.MirrorBackend(b.section, configuration))

		for b in cnf_merges:
			if useBackend(b):
				self._merges.append(Backend.MergeBackend(b.section, configuration))

		self._commands = {
			"all" : self.doAll,
			"update" : self.doUpdate,
			"upgrade" : self.doUpgrade,
			"merge" : self.doMerge,
			"clean" : self.doClean,
		}
	def isValidCommand(self, commandName):
		return commandName in self._commands

	def executeCommand(self, commandName):
		self._commands.get(commandName)()

	def doAll(self):
		self._update()
		if self._load():
			self._process()
			self._upgrade()
			self._merge()
			self._clean()

	def doUpdate(self):
		self._update()

	def doUpgrade(self):
		if self._load():
			self._process()
			self._upgrade()

	def doMerge(self):
		if self._load():
			self._process()
			self._merge()

	def doClean(self):
		if self._load():
			self._clean()

	def _update(self):
		for b in self._mirrors:
			if b.has_key('lock') and b['lock']:
				print "Skipping backend", b._name
			else:
				print "Updating backend", b._name
				b.update()

	def _load(self):
		for b in self._mirrors:
			print "Loading backend", b._name
			if not b.load():
				return False
		return True

	def _process(self):
		for b in self._mirrors:
			print "Processing backend", b._name
			b.process()

	def _upgrade(self):
		for b in self._mirrors:
			if b.has_key('lock') and b['lock']:
				print "Skipping backend", b._name
			else:
				print "Upgrading backend", b._name
				b.upgrade()

	def _clean(self):
		for b in self._mirrors + self._merges:
			if b.has_key('lock') and b['lock']:
				print "Skipping backend", b._name
			else:
				print "Clean backend", b._name
				b.clean()

	def _merge(self):
		for b in self._merges:
			print "Merging backend", b._name
			b.merge()

