from parallels.core import messages
import logging

from parallels.core.utils.windows_agent_remote_object import WindowsAgentRemoteObject
from parallels.core.utils.common import cached

logger = logging.getLogger(__name__)


class WindowsAgentPool(object):
	def __init__(self, migrator_server):
		self._migrator_server = migrator_server
		self._agents = dict()

	@staticmethod
	@cached
	def get_instance(migrator_server):
		return WindowsAgentPool(migrator_server)

	def get(self, settings):
		key = self._key(settings)
		if key not in self._agents:
			remote_object = WindowsAgentRemoteObject(settings, self._migrator_server)
			remote_object.deploy_and_connect()
			self._agents[key] = remote_object

		return self._agents[key]

	def close_all(self):
		for ip, agent in self._agents.iteritems():
			logger.debug(messages.SHUTDOWN_WINDOWS_AGENT_AT_S, ip)
			agent.shutdown()

	@staticmethod
	def _key(settings):
		return settings.ip

