import logging
import os

from parallels.common.actions.base.common_action import CommonAction
from parallels.common.logging_context import log_context
from parallels.plesks_migrator.pmm_agent import create_pmm_agent

logger = logging.getLogger(__name__)


class FetchShallowBackupAction(CommonAction):
	def get_description(self):
		return "Fetch basic information about resellers, clients and domains data from source servers"

	def get_failure_message(self, global_context):
		"""
		:type global_context: parallels.common.global_context.GlobalMigrationContext
		"""
		return (
			"Failed to fetch basic information about resellers, "
			"clients and domains data from source servers"
		)

	def run(self, global_context):
		"""
		:type global_context: parallels.common.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(u"Using the existing shallow dump for '%s'", source_id)
				else:
					agent = create_pmm_agent(global_context, source_server)
					agent.create_shallow_dump(shallow_backup_filename)
