from parallels.core import messages
from parallels.core.logging import get_logger
from parallels.core.migrator_config import PhysicalWindowsServerConfig
from parallels.core.utils.agent_pool import AgentPool
from parallels.core.utils.common import cached, is_empty
from parallels.core.utils.config_utils import get_boolean_option
from parallels.core.utils.windows_agent_remote_object import WindowsAgentRemoteObject

logger = get_logger(__name__)


class WindowsAgentPool(AgentPool):

    @staticmethod
    @cached
    def get_instance():
        """Return pool of transfer agents

        :rtype: WindowsAgentPool
        """
        return WindowsAgentPool()

    def _create_agent(self, server_config, proxy_to, allow_autodeploy):
        assert (isinstance(server_config, PhysicalWindowsServerConfig))
        remote_object = WindowsAgentRemoteObject(server_config, proxy_to)
        if (
            get_boolean_option('skip-rpc-agent-deployment', False) or
            not allow_autodeploy or
            is_empty(server_config.windows_auth.password) or
            server_config.agent_settings.skip_agent_deployment
        ):
            # according config option RPC agent should be already deployed on source server manually,
            # so just try to connect
            if proxy_to is None:
                logger.fdebug(messages.WINDOWS_AGENT_POOL_GET_MANUAL, source_ip=server_config.ip)
            else:
                logger.fdebug(
                    messages.WINDOWS_AGENT_POOL_GET_MANUAL_PROXY, source_ip=proxy_to, proxy_ip=server_config.ip
                )
            remote_object.try_connect_multiple_and_check_version()
        else:
            if proxy_to is None:
                logger.fdebug(messages.WINDOWS_AGENT_POOL_GET_AUTO, source_ip=server_config.ip)
            else:
                logger.fdebug(
                    messages.WINDOWS_AGENT_POOL_GET_AUTO_PROXY, source_ip=proxy_to, proxy_ip=server_config.ip
                )
            remote_object.deploy_and_connect()
        return remote_object
