from contextlib import contextmanager

from parallels.core.utils.common import obj
from parallels.core.registry import Registry
from parallels.core.connections.source_server import SourceServer
from parallels.core.connections.database_server import SourceDatabaseServer
from parallels.ppa.source.hsphere.remote_script import HsphereRunner


class HsphereSourceServer(SourceServer):
	def get_database_server(self, model):
		"""Get source database server

		:type model: parallels.core.dump.data_model.DatabaseServer
		"""
		if model.dbtype == 'mssql':
			access_settings = obj(
				id=self.node_id,
				is_windows=True,
				ip=model.host.split('\\')[0],
				host=model.host.split('\\')[0],
			)
		else:
			context = Registry.get_instance().get_context()
			access_settings = context.conn.get_information_servers()[self.node_id]

		return HsphereSourceDatabaseServer(access_settings, model, self)

	def __repr__(self):
		return 'HsphereSourceServer(%r)' % (self.node_id,)


class HsphereSourceDatabaseServer(SourceDatabaseServer):
	@contextmanager
	def runner(self):
		"""Overidden to execute MySQL client directly on H-Sphere MySQL node, not on H-Sphere main node"""
		with self.panel_server.runner() as runner:
			yield HsphereRunner(runner, self.ip())

	def ip(self):
		return self._access_settings.ip

	def is_windows(self):
		return self._access_settings.is_windows