from parallels.utils import obj, group_by_id, contextmanager
from parallels.common.registry import Registry
from parallels.common.connections.source_server import SourceServer
from parallels.common.connections.database_server import SourceDatabaseServer
from parallels.hsphere_migrator.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())