from contextlib import contextmanager
import logging
from parallels.common import version_tuple
from parallels.common.utils import poa_utils

from parallels.plesks_migrator.server import PleskSourceServer
from parallels.utils import cached

logger = logging.getLogger(__name__)

class PPAMoveWebspacesSourceServer(PleskSourceServer):

	def __init__(self, node_id, node_settings, migrator_server, plesk_version, mn_server):
		"""

		:param node_id: source node id
		:param node_settings: node settings from config
		:param migrator_server: server where migrator is run
		:param plesk_version: Plesk version on source (xx.xx.xx)
		:param mn_server: PPA management node
		"""
		super(PPAMoveWebspacesSourceServer, self).__init__(
				node_id, node_settings, migrator_server
		)
		self.plesk_version_string = plesk_version
		self.mn_server = mn_server
		self.ppa_host_id = poa_utils.get_host_id_by_ip(self.mn_server.poa_api(), self.ip())
		logger.debug(u"PPA host id where subscriptions web service is located: %s", self.ppa_host_id)

	@property
	@cached
	def plesk_version(self):
		return version_tuple(self.plesk_version_string)

	@contextmanager
	def runner(self):
		"""Get runner object to execute commands on the source server"""
		if self.is_windows():
			with self.mn_server.ppa_windows_node_runner(self.ppa_host_id) as runner:
				yield runner
		else:
			with self.mn_server.ppa_unix_node_runner(self.ppa_host_id) as runner:
				yield runner
