import logging
from parallels.core import messages
from parallels.core.migrator_config import MailContent
from parallels.core.actions.base.subscription_action import SubscriptionAction
from parallels.core.actions.utils.multithreading_properties import MultithreadingProperties

logger = logging.getLogger(__name__)


class CopyMailContent(SubscriptionAction):
	def get_description(self):
		return messages.ACTION_COPY_MAIL

	def get_failure_message(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		return (
			messages.FAILED_COPY_MAIL_CONTENT_SUBSCRIPTION_MOST)

	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.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		source_server = subscription.mail_source_server
		if source_server.mail_settings.mode == MailContent.NONE:
			logger.info(
				messages.LOG_NO_NEED_TO_COPY_MAILCONTENT_BECAUSE_DISABLED_BY_USER,
				subscription.name)
			return False
		else:
			return True

	def get_multithreading_properties(self):
		return MultithreadingProperties(can_use_threads=True)

	def run(self, global_context, subscription):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		safe = global_context.safe

		issues = []
		self._copy_mail_content_single_subscription(global_context, subscription, issues)
		for issue in issues:
			safe.add_issue_subscription(subscription.name, issue)

	def _copy_mail_content_single_subscription(self, global_context, subscription, issues):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		:type issues: list
		"""
		global_context.migrator._copy_mail_content_single_subscription(
			global_context.migrator_server, subscription, issues
		)