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


class HsphereSourceServer(SourceServer):
	def get_database_server(self, model, external_db_servers):
		external_db_servers_by_host = group_by_id(external_db_servers.values(), lambda s: s.host)

		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:
			if model.host in external_db_servers_by_host:
				access_settings = external_db_servers_by_host[model.host]
			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())