import os

from parallels.core import messages
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.utils.config_utils import ConfigSection
from parallels.core.utils.json_utils import read_json

logger = get_logger(__name__)


class ReadDumpAgentOptions(CommonAction):
    """Read additional options for dump agent and put them into variable in global context.

    The options are read from migrator's configuration file (config.ini) according to
    agent options schema (agent-options.json) in directory with source migration code
    for the source panel.

    Further, when deploying dump agent, these options are written to a special file
    on the source server ("config.json" ) in the directory with agent sources and used by the agent.
    """

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

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

    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.READ_AGENT_OPTIONS_ACTION_FAILURE

    def is_critical(self):
        """If action is critical or not

        :rtype: bool
        """
        return False

    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(
            # should not be logged to info.log, action is quick
            # and it makes no sense to let customer know such details
            info_log=False,
            compound=False
        )

    def run(self, global_context):
        """
        :type global_context: parallels.core.global_context.GlobalMigrationContext
        """
        for source in global_context.conn.get_sources():
            global_context.agent_options[source.id] = {}

            agent_options_schema_file = os.path.join(global_context.source_panel_dir, 'agent-options.json')

            if not os.path.exists(agent_options_schema_file):
                continue

            schema_options = read_json(agent_options_schema_file)

            if schema_options is None:
                continue

            for schema_option in schema_options:
                option_name = schema_option.get('name')
                source_server_config_section = ConfigSection(global_context.config, source.id)
                option_value = source_server_config_section.get(option_name)
                if option_value is not None:
                    global_context.agent_options[source.id][option_name] = option_value
