import logging

from parallels.core.actions.base.common_action import CommonAction
from parallels.core.utils.migrator_utils import trace_step

from parallels.shcm_web_sn.source.shcm_web_sn import messages

logger = logging.getLogger(__name__)


class FetchDumpAction(CommonAction):
	def get_description(self):
		return messages.FETCH_DATA_FROM_SOURCE_PPA_WEB_SN

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		return messages.FAILED_TO_FETCH_DATA_FROM_SOURCE_PPA_WEB_SN

	def run(self, global_context):
		"""
		:type global_context: parallels.shcm_web_sn.source.shcm_web_sn.global_context.SHCMMoveWebspacesGlobalMigrationContext
		"""
		source_server = global_context.conn.get_source_node('Source')
		logger.debug(messages.PPA_HOST_ID_OF_WEB_SERVICE.format(host_id=source_server.ppa_host_id))
		remote_backup_filename = source_server.get_session_file_path(
			u'pleskbackup.%s' % (u'zip' if source_server.is_windows() else u'tar')
		)
		with source_server.runner() as source_runner:
			with trace_step('fetch-source', messages.RUNNING_PLESKBACKUP, False, 'debug'):
				env = dict(PRODUCT_MODE=u'SHM', PLESK_DIR=source_server.plesk_dir)
				env.update(global_context.webspace_src_ctx.get_as_env())
				source_runner.sh(
					u'{pleskbackup} --domains-name {webspace_name} --configuration '
					u'--only-hosting --verbose --output-file={output_file}',
					dict(
						pleskbackup=source_server.get_bin_util_path(u'pleskbackup'),
						output_file=remote_backup_filename, webspace_name=global_context.webspace_name
					),
					stdin_content=global_context.webspace_src_ctx.get_as_json(),
					env=env)

			with trace_step('fetch-source', messages.RUNNING_DOWNLOADING_BACKUP, False, 'debug'):
				local_backup_filename = global_context.session_files.get_raw_dump_filename('Source')
				source_runner.get_file(remote_backup_filename, local_backup_filename)

			with trace_step('fetch-source', messages.RUNNING_REMOVE_BACKUP_FROM_SOURCE, False, 'debug'):
				source_runner.remove_file(remote_backup_filename)
