from parallels.common.utils.migrator_utils import normalize_domain_name
from parallels.utils import cached


class ImportedBackups(object):
	"""List of backups imported to target panel's PMM repository"""

	@staticmethod
	@cached
	def get_instance():
		"""Get single instance of that class"""
		return ImportedBackups()

	def __init__(self):
		self.backups = {}

	def add(self, backup, domain_to_xml_mapping):
		self.backups[backup] = ImportedBackup(
			backup.backup_info_file, domain_to_xml_mapping
		)

	def get_by_backup(self, backup):
		if backup not in self.backups:
			raise Exception(
				"Internal error: failed to find imported backup for specified backup object. "
				"Probable reason is that backup was never imported to target panel's PMM "
				"repository"
			)
		return self.backups[backup]

	def get_all(self):
		return self.backups.values()


class ImportedBackup(object):
	"""Backup imported to target panel's PMM repository"""

	def __init__(self, backup_info_file, file_mapping):
		self._backup_info_file = backup_info_file
		self._file_mapping = file_mapping

	@property
	def backup_info_file(self):
		return self._backup_info_file

	def get_domain_xml_path(self, domain_name):
		domain_name_normalized = normalize_domain_name(domain_name)
		if domain_name_normalized in self._file_mapping:
			return self._file_mapping[domain_name_normalized]
		else:
			raise Exception(u"Failed to find imported backup XML file for subscription")
