from parallels.source.expand import messages
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.actions.hosting_settings.import_backups import ImportedBackups
from parallels.core.utils.restore_hosting_utils import get_restore_hosting_utils


class RestoreCentralizedMailHostingSettings(SubscriptionAction):
	def get_description(self):
		return messages.RESTORE_CMAIL_SETTINGS

	def filter_subscription(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		mail_backup_filename = subscription.full_converted_mail_backup.container.backup_info_file
		hosting_backup_filename = subscription.full_converted_backup.container.backup_info_file
		return (
			# if subscription does not exist in centralized mail backup - skip this action
			subscription.converted_mail_backup is not None
			and
			# if mail backup is the same as main backup - all settings will be restored
			# when restoring main backup, nothing to do in this action
			mail_backup_filename != hosting_backup_filename
		)

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return messages.FAILED_TO_RESTORE_CMAIL_SETTINGS % subscription.name

	def is_critical(self):
		"""If action is critical or not

		If action is critical and it failed for a subscription, migration tool
		won't run the next operations for the subscription.

		:rtype: bool
		"""
		return False

	def run(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		imported_backup = ImportedBackups.get_instance().get_by_backup(subscription.full_converted_mail_backup)
		subscription_backup_xml = imported_backup.get_domain_xml_path(subscription.name)

		restore_hosting_utils = get_restore_hosting_utils(global_context.conn.target.plesk_server)

		restore_hosting_utils.restore_hosting_settings(
			subscription.name, subscription_backup_xml, global_context.safe,
			settings_description=u"hosting settings",
			disable_apsmail_provisioning=subscription.is_mail_assimilate
		)
