from parallels.core import messages
import logging
from textwrap import dedent

from parallels.core.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.core.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 messages.REMOVE_DISABLED_MAILSYSTEM_WITHOUT_RESOURCE_IN

	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_REMOVE_DISABLED_MAILSYSTEM_FOR_SUBSCRIPTION % (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.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		:type subscription_backup: parallels.core.dump.data_model.Subscription
		"""
		if subscription_backup.mailsystem is not None:
			if (
				subscription.mail_target_server is None 
				and not subscription_backup.mailsystem.enabled
			):
				subscription_backup.remove_mailsystems()
				logger.debug(
					dedent(messages.SUBSCRIPTION_S_DISABLED_MAIL_AND_SERVICE % subscription.name
					)
				)
