from parallels.source.custom import messages
import logging
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.content.mail.rsync import SourceMailDirectory, CopyMailRsync
from parallels.core.utils.paths.mail_paths import MailboxDirectory

logger = logging.getLogger(__name__)


class CopyMailMessages(SubscriptionAction):
	def get_description(self):
		"""
		:rtype: basestring
		"""
		return "Copy mail messages"

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		:rtype: basestring
		"""
		return messages.ACTION_COPY_MAIL_MESSAGES_FAILURE

	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 filter_subscription(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.custom_panel_migrator.migrated_subscription.CustomPanelMigratedSubscription
		"""
		return subscription.light_backup is not None

	def run(self, global_context, subscription):
		"""
		:type global_context: parallels.custom_panel_migrator.global_context.CustomPanelGlobalMigrationContext
		:type subscription: parallels.custom_panel_migrator.migrated_subscription.CustomPanelMigratedSubscription
		"""
		copy_mail = CopyMailRsync(CustomPanelSourceMailDirectory)
		copy_mail.copy_mail(global_context, None, subscription, None)


class CustomPanelSourceMailDirectory(SourceMailDirectory):
	"""Provide paths to directories with mail messages on source server according to the light backup"""

	def prepare(self):
		"""
		:rtype: list[tuple(str, parallels.core.content.mail.rsync.MailHostingPath]]
		"""
		directories = []

		for mailbox in self.subscription.light_backup.iter_mailboxes():
			if mailbox.source_directory is None:
				continue
			if mailbox.domain_name.encode('idna') != self.domain.name.encode('idna'):
				continue

			directories.append((mailbox.source_directory, MailboxDirectory(mailbox.short_name)))

		return directories
