from parallels.common import messages
from parallels.common.actions.base.subscription_backup_action \
	import SubscriptionBackupAction
from parallels.common.actions.utils.logging_properties \
	import LoggingProperties
from parallels.common.target_panels import TargetPanels
from parallels.utils.ip import is_ipv4, is_ipv6


class ChangeCatchAllRedirect(SubscriptionBackupAction):
	def get_description(self):
		return messages.CHANGE_SERVER_CATCHALL_REDIRECT_DISCART

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

	def get_logging_properties(self):
		return LoggingProperties(info_log=False)

	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_subscription_backup(
		self, global_context, subscription, subscription_backup
	):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		if global_context.target_panel != TargetPanels.PPA:
			# applicable to PPA only, for Plesk we can restore catch all
			# pointing to external mail server without any issues
			return

		# catch-all is a subscription wide option, no need to check addon
		# domains and subdomains
		if subscription_backup.mailsystem is not None: 
			catch_all_value = subscription_backup.mailsystem.get_catch_all()
			if catch_all_value is not None and (is_ipv4(catch_all_value) or is_ipv6(catch_all_value)):
				subscription_backup.mailsystem.replace_catch_all('discard')
