import logging
from contextlib import closing

import connections

from parallels.common.migrator import Migrator as CommonMigrator
from parallels.custom_panel_migrator.backup_creator import BackupCreator
from parallels.custom_panel_migrator.session_files import CustomPanelSessionFiles
from parallels.custom_panel_migrator.workflow import FromCustomPanelWorkflow
from parallels.custom_panel_migrator.global_context import CustomPanelGlobalMigrationContext

logger = logging.getLogger(__name__)


class Migrator(CommonMigrator):
	logger = logging.getLogger(__name__)

	def __init__(self, config):
		super(Migrator, self).__init__(config)
		self.global_context.source_plesks = None

	def iter_shallow_plesk_backups(self):
		return self.iter_plesk_backups()

	def iter_plesk_backups(self):
		for source_info in self.global_context.get_sources_info():
			yield source_info.id, source_info.load_raw_backup()

	def iter_converted_plesk_backups(self):
		for source_info in self.global_context.get_sources_info():
			with closing(self.load_converted_plesk_backup(source_info.id)) as backup:
				yield source_info.id, backup

	def iter_converted_backups(self):
		return self.iter_converted_plesk_backups()

	def create_full_backup_from_light_backup(self):
		backup_creator = BackupCreator()
		backup_creator.write_full_backup(
			self.global_context.options.source_file,
			self.global_context.options.source_format,
			self.global_context.options.target_file
		)

	def _subscription_is_windows(self, subscription_name, plesk_id=None):
		if plesk_id is not None:
			return self.get_raw_plesk_backup(plesk_id).is_windows
		for _, backup in self.iter_plesk_backups():
			if backup.has_subscription(subscription_name):
				return backup.is_windows
		raise Exception('Unable to retrieve backup containing subscription "%s" % subscription_name')

	def _get_source_servers(self):
		return {}

	def _get_source_mail_node(self, subscription_name):
		return None

	def _load_connections_configuration(self):
		return connections.MigratorConnections(self.config, self._get_target_panel())

	def _create_workflow(self):
		return FromCustomPanelWorkflow()

	def _create_global_context(self):
		return CustomPanelGlobalMigrationContext()

	def _create_session_files(self):
		return CustomPanelSessionFiles(self.conn, self._get_migrator_server())