from parallels.core.actions.base.common_action import CommonAction
from parallels.core.actions.utils.logging_properties import LoggingProperties
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.agent_pool import get_agent_run_command
from parallels.plesk.source.custom.utils.config_getter import get_configs, ConfigFilter

logger = get_logger(__name__)


class AgentStartInfo(CommonAction):
    """Inform where to search deployed agent on source server and how to run"""

    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_AGENT_START_INFO

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

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

    def get_logging_properties(self):
        """Get how action should be logged to migration tools end-user

        :rtype: parallels.core.actions.utils.logging_properties.LoggingProperties
        """
        return LoggingProperties(compound=False)

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

        :type global_context: parallels.plesk.source.custom.global_context.CustomPanelGlobalMigrationContext
        :rtype: None
        """
        need_deploy_agent = get_configs(global_context, ConfigFilter.NEED_DEPLOY_AGENT)
        if len(need_deploy_agent) == 0:
            logger.finfo(messages.NO_AGENT_MANUAL_START_INFO)
        else:
            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)
                command = get_agent_run_command(source_server, source_panel)
                logger.finfo(
                    messages.AGENT_MANUAL_START_INFO,
                    agent=source_panel.source_panel_id, server=source_server.description(), command=command
                )
