import os
import logging

from parallels.utils import cached
from parallels.common.plesk_backup import save_backup_tar

class PmmDumper(object):
	"""Execute the deployed PMM agent and download dump files.
	
	The supported backup format is that of Plesk 10 or earlier: a single file
	with dump XML.
	"""
	logger = logging.getLogger(__name__)

	def __init__(self, source_server, migrator_host, agent):
		"""Object constructor.

		Arguments:
			source_server:
				An object, that constructs locations for temporary file names
				on source server
			agent:
				PMM migration agent, an instance of PmmMigrationAgentBase
		"""
		self.source_server = source_server
		self.migrator_host = migrator_host
		self.agent = agent

	def create_dump(self, filename):
		"""Create migration dump and download dump files."""
		self.logger.debug(u"Run PMM agent to create dump XML")
		self.agent.run_agent(self.dump_file, self.dump_log)

		self.logger.debug(u"Pack dump XML into dump archive")
		with open(self.dump_file) as dump_xml_fp:
			save_backup_tar(dump_xml_fp.read(), filename)

	def run_premigration_check(self):
		"""
		Run checker script, download log file and generate report

		:return: path to generated report file
		"""
		self.agent.run_pre_migration(
			self.premigration_report_file,
			self.premigration_log_file
		)

		return self.premigration_report_file

	# ----------------------- migration PMM agent file locations --------------
	# Files are located on a per-execution directory. Each time you run 
	# migration tools process - a new name for a directory is generated.

	@property
	def premigration_log_file(self):
		return os.path.join(self._get_pmm_session_dir(), 'pre-migration.log')

	@property
	def dump_file(self):
		return os.path.join(self._get_pmm_session_dir(), 'dump.xml')

	@property
	def dump_log(self):
		return os.path.join(self._get_pmm_session_dir(), 'dump.log')

	@cached
	def _get_pmm_session_dir(self):
		"""Create a session directory for PPM files."""
		dirname = self.migrator_host.make_session_tmpdir('pmm-agent')
		return dirname

	@property
	def premigration_report_file(self):
		"""Location pre-migration execution results."""
		return os.path.join(self._get_pmm_session_dir(), 'pre-migration.xml')

class PmmDumper12(PmmDumper):
	"""Migration dumper, that creates dumps in Plesk 12 format."""
	def create_dump(self, filename):
		"""Run migration agent and create a migration dump."""
		self.logger.debug( u"Creating migraton dump '%s'" % filename)
		self.agent.run_agent(filename, self.dump_log)
