import logging

from parallels.common.actions.base.subscription_action import SubscriptionAction
from parallels.common.utils import migrator_utils
from parallels.common.utils import subscription_filter
from parallels.common.utils import ssh_utils
from parallels.common import MigrationError

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):
		return "Failed to copy web files for subscription '%s'" % (subscription.name)

	def filter_subscription(self, global_context, subscription):
		return subscription_filter.unix_with_virtual_hosting(
			subscription
		)

	def run(self, global_context, subscription):
		source_server = subscription.web_source_server
		target_server = subscription.web_target_server

		tocopy = self._list_files_to_copy(global_context, subscription)

		with \
			source_server.runner() as runner_source, \
			target_server.runner() as runner_target, \
			ssh_utils.public_key_ssh_access_runner(
				runner_target,  runner_source
			) as key_pathname:
				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_pathname,
							item.exclude,
							item.skip_if_source_not_exists
						)
				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()
