from parallels.core import messages
from parallels.core.utils.migrator_utils import normalize_domain_name
from parallels.core.utils.common 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(
				messages.INTERNAL_ERROR_FAILED_FIND_IMPORTED_BACKUP)
		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(messages.FAILED_FIND_IMPORTED_BACKUP_XML_FILE)
