from parallels.plesk.source.plesk import messages
import logging
import os

from parallels.core.actions.base.common_action import CommonAction
from parallels.core.logging_context import log_context
from parallels.plesk.source.plesk.pmm_agent import create_pmm_agent

logger = logging.getLogger(__name__)


class FetchShallowBackupAction(CommonAction):
	def get_description(self):
		return messages.ACTION_FETCH_SHALLOW_BACKUP_DESCRIPTION

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

	def run(self, global_context):
		"""
		:type global_context: parallels.core.global_context.GlobalMigrationContext
		"""
		for source_id in global_context.conn.get_source_plesks():
			source_server = global_context.conn.get_source_node(source_id)
			session_files = global_context.session_files
			shallow_backup_filename = session_files.get_path_to_shallow_plesk_backup(
				source_id)

			with log_context(source_id):
				if (
					not global_context.options.reload_source_data and
					os.path.exists(shallow_backup_filename)
				):
					logger.info(messages.LOG_USING_CACHED_SHALLOW_DUMP, source_id)
				else:
					global_context.dump_agent = create_pmm_agent(global_context, source_server)
					global_context.dump_agent.create_shallow_dump(shallow_backup_filename)
