import logging

from parallels.common.actions.base.subscription_action import SubscriptionAction
from parallels.common import migrator_config
from parallels.common.actions.utils.multithreading_properties import MultithreadingProperties
from parallels.common.utils import migrator_utils
from parallels.common.utils import subscription_filter
from parallels.common import MigrationError
from parallels.hosting_analyser.hosting_analyser import HostingAnalyser

logger = logging.getLogger(__name__)


class CopyUnixWebContentBase(SubscriptionAction):
	"""Base class to copy web content for Unix servers"""

	def get_description(self):
		return "Copy web files from Unix servers"

	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 copy web files 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 get_multithreading_properties(self):
		return MultithreadingProperties(can_use_threads=True)

	def filter_subscription(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return subscription_filter.unix_with_virtual_hosting(
			subscription
		)

	def run(self, global_context, subscription):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		source_server = subscription.web_source_server
		target_server = subscription.web_target_server

		user_mapping = {}
		group_mapping = {}

		if source_server.apache_user != target_server.apache_user:
			user_mapping[source_server.apache_user] = target_server.apache_user
		if source_server.apache_group != target_server.apache_group:
			group_mapping[source_server.apache_group] = target_server.apache_group

		tocopy = self._list_files_to_copy(global_context, subscription)
		rsync_additional_args = migrator_config.read_rsync_additional_args(global_context.config)

		# choose transfer strategy
		hosting_analyser = HostingAnalyser(global_context.migrator_server)
		if rsync_additional_args.count('-z') == 0 and hosting_analyser.is_compression_needed(subscription):
			rsync_additional_args.append('-z')

		key_info = global_context.ssh_key_pool.get(source_server, target_server)
		with \
			source_server.runner() as runner_source, \
			target_server.runner() as runner_target:
				try:
					for item in tocopy:
						migrator_utils.copy_directory_content_unix(
							source_server.ip(),
							source_server.user(),
							runner_source,
							runner_target,
							item.source_subdir,
							target_server.vhosts_dir + '/' + item.target_subdir,
							key_info.key_pathname,
							item.exclude,
							item.skip_if_source_not_exists,
							rsync_additional_args=rsync_additional_args,
							user_mapping=user_mapping,
							group_mapping=group_mapping,
							source_rsync_bin=source_server.rsync_bin
						)
				except Exception as e:
					logger.debug(u"Exception: ", exc_info=e)
					raise MigrationError((
						u"Rsync failed to copy files from the source (%s) to the target server (%s): %s\n"
						u"""1. This could happen because of a network connection issue.
						Retry copying the files with the help of the "copy-content" command.\n"""
						u"2. Check whether rsync is installed and configured on the source server."
					) % (source_server.description(), target_server.description(), str(e)))

	def _list_files_to_copy(self, global_context, subscription):
		"""Make a list of source server directories to be transferred.

		Return a list of (source directory -> destination directory) mappings.
		Override in child classes.
		"""
		raise NotImplementedError()
