from parallels.core.logging import get_logger
from parallels.core.utils.pmm.agent import DumpAll, PmmMigrationAgentBase
from parallels.plesk.source.helm3.helm3_agent import Helm3Agent

logger = get_logger(__name__)


class Helm3PmmMigrationAgent(PmmMigrationAgentBase):
    def _deploy(self):
        pass  # no explicit deployment is required, all deployment is performed automatically by Helm3Agent class

    def _run(self, dump_xml_filename, dump_log_filename, selection=DumpAll()):
        remote_log_filename = self._source_server.get_session_file_path('dump.log')
        remote_backup_xml_filename = self._source_server.get_session_file_path("backup.xml")

        with self._source_server.runner() as runner:
            runner.remove_file(remote_log_filename)
            runner.remove_file(remote_backup_xml_filename)

        helm_agent = Helm3Agent(self._source_server)
        args = ['--create-full-dump']

        filter_xml_contents = selection.get_filter_xml()
        if filter_xml_contents is not None:
            remote_filter_filename = self._source_server.get_session_file_path('filter.xml')
            with self._source_server.runner() as runner:
                runner.upload_file_content(remote_filter_filename, filter_xml_contents)
            args.extend(["--filter", remote_filter_filename])

        try:
            helm_agent.run(args, redirect_output_file=remote_log_filename)
        finally:
            # Try to download log file anyway, even if there were issues
            with self._source_server.runner() as runner:
                if runner.file_exists(remote_log_filename):
                    runner.get_file(remote_log_filename, dump_log_filename)

        with self._source_server.runner() as runner:
            runner.get_file(remote_backup_xml_filename, dump_xml_filename)

    def _is_dump_agent_creates_archive(self):
        """Whether dump agent creates ready to use dump archive (ZIP or TAR). If False then agent creates plain XML.

        :rtype: bool
        """
        return False

    def _is_dump_version_upgrade_required(self):
        """Whether dump agent creates dump in old format (< 17.0), and upgrade is required to use with target Plesk 18

        :rtype: bool
        """
        return True
