from parallels.ppa.source.hsphere import messages
from parallels.core.actions.base.subscription_backup_action import SubscriptionBackupAction
from parallels.core.checking import Problem
from parallels.core.utils.common import format_list


class MailsystemOnSubdomains(SubscriptionBackupAction):
	def get_description(self):
		return messages.ACTION_CHECK_MAIL_ON_SUBDOMAINS

	def get_failure_message(self, global_context, subscription):
		return messages.FAILED_TO_CHECK_MAIL_ON_SUBDOMAINS % 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']:
						# just skip the system mailboxes
						continue
					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,
					messages.TARGET_DOES_NOT_SUPPORT_SUBDOMAIN_MAIL_BOX % format_list(subdomains_with_mailboxes)
				),
				messages.PRESERVE_CONTENT_OF_MAILBOXES_IF_NECESSARY)

		if len(subdomains_with_mailboxes) > 0:
			subscription.add_report_issue(
				global_context.pre_check_report,
				Problem(
					'mail_on_subdomains', Problem.WARNING,
					messages.TARGET_DOES_NOT_SUPPORT_SUBDOMAIN_MAIL_ACCOUNT % format_list(subdomains_with_mailboxes)
				),
				u""
			)
