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

from parallels.core.migrator import trace
from parallels.plesk.source.legacy.pmm_pre_migration import add_report_xml_issues
from parallels.core.migrator import Migrator as CommonMigrator
from parallels.core.utils.common import cached

class PmmUnixMigrator(CommonMigrator):
	"""Unix single-server migrator based on PMM migration agent.
	Implements functions common to all single-server PMM migration agents
	like fetching backup with PMM agent and pre-migration checks.
	"""

	logger = logging.getLogger(__name__)

	def __init__(self, config, settings):
		super(PmmUnixMigrator, self).__init__(config)
		self.settings = settings

	# ======================== fetch data from source panel ===================

	@trace('fetch-source', messages.FETCH_INFO_FROM_SOURCE_SERVERS)
	def _fetch_source(self, options, overwrite):

		dumpfile = self.get_raw_dump_filename(self._get_settings().id)
		if all([
			not overwrite,
			os.path.exists(dumpfile),
			os.path.exists(self.premigration_report_file)
		]):
			self.logger.info(messages.MIGRATION_DUMP_ALREADY_EXISTS_SKIP)
		else:
			self._get_dump_agent().create_dump(dumpfile, True)

	# ======================== pre-migration checks ===========================

	def _check_additional(self, root_report):
		check_report_file = self._get_dump_agent().check()

		# add issues from XML report generated by PMM agent
		add_report_xml_issues(
			backup=self._load_raw_panel_dump(),
			xml_report_filename=check_report_file,
			report=root_report.subtarget('Source server', self.settings.PANEL_ID)
		)

	# ----------------------- migration cached file locations -----------------
	# these files are cached which means if you run fetch-source the second 
	# time, and the previous run was succesfull, then migrator
	# won't reload data and rewrite these files, but rather will take info
	# from these files

	@property
	def premigration_report_file(self):
		return self._get_session_file_path('pre-migration.xml')

	# ======================== utility functions ==============================

	def _load_raw_panel_dump(self):
		return self.load_raw_dump(self.source_servers[self.settings.PANEL_ID])

	def _get_settings(self):
		"""Always use the first specified source panel"""
		(_, settings) = self.source_servers.items()[0]
		settings.agent_home = posixpath.join(
			settings.session_dir, 'migration_agent'
		)
		return settings

	@cached
	def _get_dump_agent(self):
		raise NotImplementedError()
