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.plesk.source.custom import messages
from parallels.plesk.source.custom.utils.config_getter import get_configs, ConfigFilter, \
    configs_with_source_server_exist

logger = get_logger(__name__)


class DeployAgent(CommonAction):
    """Deploy agent and required components to source server"""

    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_DEPLOY_AGENT

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

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

    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_deploy_agent = get_configs(global_context, ConfigFilter.NEED_DEPLOY_AGENT)
        for config in hd_generation_can_be_skipped:
            if config not in need_deploy_agent:
                logger.finfo(messages.SKIP_DEPLOY_AGENT, hosting_description_file=config.path)

        for hosting_description_config in need_deploy_agent:
            source_server = global_context.conn.get_source_by_id(hosting_description_config.source_id)
            source_panel = get_additional_source_panel(global_context)
            global_context.agent_pool.deploy(source_server, source_panel)
