from parallels.common.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.common.checking import Problem
from parallels.utils import format_list


class MailsystemOnSubdomains(SubscriptionBackupAction):
	def get_description(self):
		return "Check mail on subdomains"

	def get_failure_message(self, global_context, subscription):
		return "Failed to check mail on subdomains 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 _run_subscription_backup(
		self, global_context, subscription, subscription_backup
	):
		subdomains_with_mailboxes = set()
		subdomains_with_mailnames = set()
		for site in subscription_backup.iter_sites():
			if site.parent_domain_name is not None:
				# find out if there were mailboxes or mailnames and a warning must be issued
				for mailbox in site.iter_mailboxes():
					if mailbox.name in ['webmaster', 'postmaster']:
						continue # just skip the system mailboxes
					else:
						if mailbox.enabled:
							subdomains_with_mailboxes.update({site.name})
						else:
							subdomains_with_mailnames.update({site.name})

		if len(subdomains_with_mailboxes) > 0:
			subscription.add_report_issue(
				global_context.pre_check_report,
				Problem(
					'mail_on_subdomains', Problem.WARNING,
					u"PPA does not support mail accounts on subdomains. The mail boxes of the following subdomains will not be transferred: %s" % format_list(subdomains_with_mailboxes)
				),
				u"Preserve the content of these mailboxes, if necessary."
			)

		if len(subdomains_with_mailboxes) > 0:
			subscription.add_report_issue(
				global_context.pre_check_report,
				Problem(
					'mail_on_subdomains', Problem.WARNING,
					u"PPA does not support mail accounts on subdomains. The mail accounts of the following subdomains will not be transferred: %s" % format_list(subdomains_with_mailboxes)
				),
				u""
			)
