import os

from parallels.core.logging import get_logger
from parallels.core.logging import log_context
from parallels.core.actions.base.common_action import CommonAction
from parallels.plesk.source.plesk import messages
from parallels.plesk.source.plesk.pmm_agent.utils import create_pmm_agent

logger = get_logger(__name__)


class FetchShallowBackupAction(CommonAction):
    def get_description(self):
        return messages.ACTION_FETCH_SHALLOW_BACKUP_DESCRIPTION

    def get_failure_message(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        return (
            messages.ACTION_FETCH_SHALLOW_BACKUP_FAILURE)

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        for source_id in global_context.conn.get_source_plesks():
            source_server = global_context.conn.get_source_node(source_id)
            session_files = global_context.session_files
            shallow_backup_filename = session_files.get_path_to_shallow_plesk_backup(
                source_id)

            with log_context(source_id):
                if (
                    not global_context.options.reload_source_data and
                    os.path.exists(shallow_backup_filename)
                ):
                    logger.info(messages.LOG_USING_CACHED_SHALLOW_DUMP, source_id)
                else:
                    dump_agent = create_pmm_agent(global_context, source_server)
                    dump_agent.create_shallow_dump(shallow_backup_filename)