import os

from parallels.core.logging import get_logger
from parallels.plesk.source.legacy import messages
from parallels.plesk.source.legacy.pmm_pre_migration import add_report_xml_issues
from parallels.core.migrator import Migrator as CommonMigrator

logger = get_logger(__name__)


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.
    """

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

    def _fetch_source(self, options, overwrite):
        dumpfile = self.get_raw_dump_filename(self.global_context.settings.PANEL_ID)
        if not overwrite and os.path.exists(dumpfile):
            logger.info(messages.MIGRATION_DUMP_ALREADY_EXISTS_SKIP)
        else:
            self.global_context.dump_agent.create_dump(dumpfile)

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

    def _check_additional(self, root_report):
        check_report_file = self.global_context.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.global_context.settings.PANEL_ID)
        )

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

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