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


class CatchAllRedirect(SubscriptionBackupAction):
	def get_description(self):
		return "Check catch-all redirects to another server"

	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 check catch all redirects for subscription '%s'" % 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

		if subscription_backup.mailsystem is not None: # catch-all is a subscription wide option,
			#  no need to check addon domains and subdomains
			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.add_report_issue(
					global_context.pre_check_report,
					Problem(
						'catch_all_redirect_to_external_server', Problem.WARNING, 
						u"On the source server, all mail that was sent to "
						u"nonexistent mail users was redirected to external mail server '%s'. "
						u"PPA does not support such option." % (
							catch_all_value,
						)
					),
					"All mail that is sent to nonexistent users will be rejected by PPA mail server." 
				)
