import os
import posixpath
import logging

from parallels.common.migrator import trace
from parallels.pmm_unix_migrator.pmm_pre_migration import add_report_xml_issues
from parallels.common.migrator import Migrator as CommonMigrator
from parallels.utils 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', u'fetch info from source servers')
	def _fetch_source(self, options, overwrite):

		dumpfile = self.get_path_to_raw_plesk_backup_by_settings(
			self._get_settings())
		if all([
			not overwrite,
			os.path.exists(dumpfile),
			os.path.exists(self.premigration_report_file)
		]):
			self.logger.info(u"Migration dump already exists, skip loading")
		else:
			self._get_pmm_agent().create_dump(dumpfile, True)

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

	def _check_additional(self, root_report, ppa_existing_objects):
		check_report_file = self._get_pmm_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_plesk_backup(self.source_plesks[self.settings.PANEL_ID])

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

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