from contextlib import contextmanager
from parallels.ppa.source.hsphere import messages
from parallels.core.utils.common import obj
from parallels.ppa.source.hsphere.remote_script import HsphereRunner


class HSphereSourceMailServer(object):
	"""Retrieve H-Sphere source mail server information, interact with server"""

	def __init__(self, conn, ip_address):
		"""
		conn - instance of HsphereMigratorConnections
		"""
		self.conn = conn
		self.ip_address = ip_address

	@contextmanager
	def runner(self):
		"""Get runner object to execute commands on the source server"""
		with self.conn.hsphere_cp_runner() as cp_runner:
			yield HsphereRunner(cp_runner, self.ip_address)

	def is_windows(self):
		"""Return True if source server is Windows server, 
		False if source server is Unix server. H-Sphere source 
		mail server is always Unix"""
		return False

	def description(self):
		"""Return brief server description which should help end customer
		to identify server and which should be used in all messages"""
		return messages.SOURCE_MAIL_SERVER_DESCRIPTION % (self.ip(),)

	def ip(self):
		"""Return main IP address of the server"""
		return self.ip_address

	def user(self):
		return 'root'

	def settings(self):
		# HACK: set default port for server to be compatible with common code
		return obj(ssh_auth=obj(port=22))

	@property
	def mail_settings(self):
		"""Return copy mail content configuration"""
		return self.conn.hsphere.conn_settings.mail_settings

	def mail_imap_encryption(self):
		"""Return IMAP sync encryption mode (no encryption/SSL/TLS) 

		See parallels.core.connections.config.MailImapEncryption
		for possible values
		"""
		return self.mail_settings.mail_imap_encryption

	def __repr__(self):
		return 'HSphereSourceMailServer(%r)' % (self.ip_address,)

	def __hash__(self):
		"""Implemented for using objects as dicitionary keys, 
		for the purpose of grouping"""
		return hash(self.ip_address)

	def __eq__(self, another):
		"""Implement for using objects as dicitionary keys, 
		for the purpose of grouping"""
		return self.ip_address == another.ip_address
