from parallels.core.actions.base.common_action import CommonAction
from parallels.core.logging import get_logger
from parallels.core.panels import get_additional_source_panel
from parallels.core.runners.base import BaseRunner
from parallels.plesk.source.custom import messages
from parallels.plesk.source.custom.utils.agent_pool import AgentPool, run_agent
from parallels.plesk.source.custom.utils.config_getter import get_configs, ConfigFilter, \
    configs_with_source_server_exist

logger = get_logger(__name__)


class CreateHostingDescription(CommonAction):
    """Create hosting description using custom script"""

    def get_failure_message(self, global_context):
        """Get message for situation when action failed

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: str | unicode
        """
        return messages.ACTION_FAILED_CREATE_HOSTING_DESCRIPTION

    def get_description(self):
        """Get short description of action as string

        :rtype: str | unicode
        """
        return messages.ACTION_DESCRIPTION_CREATE_HOSTING_DESCRIPTION

    def filter_action(self, global_context):
        """Check whether we should run this action or not. By default True - action should be executed.

        Arguments:
        - global_context - registry with different objects that reused among different actions

        :type global_context: parallels.core.global_context.GlobalMigrationContext
        :rtype: bool
        """
        return configs_with_source_server_exist(global_context)

    def run(self, global_context):
        """Run action

        :type global_context: parallels.plesk.source.custom.global_context.CustomPanelGlobalMigrationContext
        :rtype: None
        """
        hd_generation_can_be_skipped = get_configs(global_context, ConfigFilter.HD_GENERATION_CAN_BE_SKIPPED)
        need_generate_hd = get_configs(global_context, ConfigFilter.NEED_GENERATE_HD)
        for config in hd_generation_can_be_skipped:
            if config not in need_generate_hd:
                logger.finfo(messages.SKIP_LOADING_HOSTING_DESCRIPTION_FILE, hosting_description_file=config.path)

        for config in need_generate_hd:
            source_server = global_context.conn.get_source_by_id(config.source_id)
            self._create_hosing_description(global_context, source_server, config)

            # remove existing dumps to force refresh them
            source_id = config.source_id
            with global_context.migrator_server.runner() as runner:
                runner.remove_file(global_context.session_files.get_raw_dump_filename(source_id))
                runner.remove_file(global_context.session_files.get_path_to_cut_plesk_backup(source_id))
                runner.remove_file(global_context.session_files.get_converted_dump_filename(source_id))

    @classmethod
    def _create_hosing_description(cls, global_context, source_server, hosting_description_config):
        """Do action on the source server

        :type global_context: parallels.plesk.source.custom.global_context.CustomPanelGlobalMigrationContext
        :type source_server: parallels.core.connections.source_server.SourceServer
        :type hosting_description_config: parallels.plesk.hosting_description.config.HostingDescriptionConfig
        :rtype: None
        """
        source_panel = get_additional_source_panel(global_context)
        agent_session_file_path = source_server.get_session_file_path('agent')
        remote_hosting_description = source_server.join_file_path(
            agent_session_file_path, source_panel.hosting_description_filename
        )
        agent_output_dir = source_server.join_file_path(agent_session_file_path, AgentPool.AGENT_OUTPUT_DIR)

        try:
            run_agent(source_server, source_panel)
            logger.finfo(messages.GET_HOSTING_DESCRIPTION_FROM_SOURCE)
            with source_server.runner() as runner_source:
                assert isinstance(runner_source, BaseRunner)
                runner_source.get_file(remote_hosting_description, hosting_description_config.path)
                target_output_dir = global_context.session_files.get_target_output_dir(
                    hosting_description_config.source_id
                )
                runner_source.download_directory(agent_output_dir, target_output_dir)
        finally:
            with source_server.runner() as runner_source:
                assert isinstance(runner_source, BaseRunner)
                logger.fdebug(messages.REMOVE_AGENT_EXECUTION_RESULTS_FROM_SOURCE)
                runner_source.remove_file(remote_hosting_description)
                runner_source.remove_directory(agent_output_dir)
