import logging
from textwrap import dedent

from parallels.common.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.common.actions.utils.logging_properties \
	import LoggingProperties


logger = logging.getLogger(__name__)


class RemoveDisabledMailsystemWithoutResource(SubscriptionBackupAction):
	"""In PPA, pleskresore does not restore domain with disabled mailsystem if
	mail resource is absent, so we remowe mailsystem in this case"""

	def get_description(self):
		return "Remove disabled mailsystem without resource in backup"

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return "Failed to remove disabled mailsystem for subscription '%s'" % (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 get_logging_properties(self):
		return LoggingProperties(info_log=False)

	def _run_subscription_backup(
		self, global_context, subscription, subscription_backup
	):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		if subscription_backup.mailsystem is not None:
			if (
				subscription.mail_target_server is None 
				and not subscription.mailsystem.enabled
			):
				subscription_backup.remove_mailsystems()
				logger.debug(
					dedent(u"""\
Subscription '%s' has disabled mail and service template does not have mail
resource, so mailsystem node was removed.""" % subscription.name
					)
				)
