from parallels.core.logging import get_logger
from parallels.core.utils.pmm.agent import DumpAll, DumpSelected
from parallels.core.utils.yaml_utils import read_yaml, write_yaml
from parallels.plesk.source.helm3 import messages
from parallels.core.actions.base.common_action import CommonAction
from parallels.plesk.source.helm3.backup_agent import Helm3PmmMigrationAgent

logger = get_logger(__name__)


class FetchData(CommonAction):
    """Fetch backup dump from source Helm 3 panel"""

    def get_description(self):
        return messages.ACTION_FETCH_DATA_FROM_SOURCE_DESCRIPTION

    def get_failure_message(self, global_context):
        """
        :type global_context: parallels.plesk.source.helm3.global_context.Helm3GlobalMigrationContext
        """
        return messages.ACTION_FETCH_DATA_FROM_SOURCE_FAILED

    def run(self, global_context):
        """
        :type global_context: parallels.plesk.source.helm3.global_context.Helm3GlobalMigrationContext
        """
        logger.info(messages.FETCH_HELM_SERVERS_INFO)
        overwrite = global_context.options.reload_source_data
        selection_filename = global_context.session_files.get_path_to_raw_plesk_backup_selection('helm3')

        if global_context.migration_list_data is None:
            selection = DumpAll()
        else:
            selection = DumpSelected(
                resellers=set(global_context.migration_list_data.resellers),
                clients=set(global_context.migration_list_data.customers_mapping.keys()),
                domains=set(global_context.migration_list_data.subscriptions_mapping.keys())
            )

        with global_context.migrator_server.runner() as local_runner:
            if local_runner.file_exists(selection_filename):
                previous_selection = read_yaml(selection_filename)
            else:
                previous_selection = None

            dump_filename = global_context.session_files.get_raw_dump_filename('helm3')
            if (
                previous_selection is not None and
                previous_selection.covers(selection) and
                local_runner.file_exists(dump_filename) and
                not overwrite
            ):
                logger.info(messages.SKIP_LOADING_CACHED_HELM_DATA_FILES)
            else:
                if local_runner.file_exists(selection_filename):
                    local_runner.remove_file(selection_filename)

                agent = Helm3PmmMigrationAgent(
                    global_context, global_context.conn.helm3.get_main_source_server()
                )
                agent.create_dump(dump_filename, selection)

                write_yaml(selection_filename, selection)
