from contextlib import contextmanager
import logging

from parallels.shm_web_sn.source.shm_web_sn import messages
from parallels.core import version_tuple
from parallels.ppa.utils import poa_utils
from parallels.plesk.source.plesk.server import PleskSourceServer
from parallels.core.utils.common 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(messages.PPA_HOST_ID_OF_WEB_SERVICE, 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
