from contextlib import contextmanager
import ntpath

from parallels.utils import ip as ip_utils
from parallels.utils import cached
from parallels.common.connections.database_server import TargetDatabaseServer


class PleskDatabaseTargetServer(TargetDatabaseServer):
	def __init__(self, db_type, host, port, login, password, panel_server):
		"""
		Arguments:
		- panel_server - instance of PleskTargetServer
		"""
		self.db_type = db_type
		self._host = host
		self._port = port
		self._login = login
		self._password = password
		self._panel_server = panel_server

	@contextmanager
	def runner(self):
		with self._panel_server.runner() as runner:
			yield runner

	def is_windows(self):
		if self.is_external():
			if self.db_type == 'mssql':
				return True
			raise Exception(
				u'Trying to get OS type for external database server. '
				u'Getting OS type for external database server is not implemented.'
			)
		return self._panel_server.is_windows()

	@cached
	def ip(self):
		if self.host() == 'localhost':
			# pleskrestore restores 'localhost' databases to Plesk's main node
			# and Plesk's main node is PPA management node
			return self._panel_server.ip()
		else:
			# host may contain MS SQL instance name, e.g.
			# 10.50.52.100\MSSQLSERVER2008
			host = self.host().split('\\')[0]
			if host == '.':
				# the same as localhost
				return self._panel_server.ip()
			else:
				return ip_utils.resolve(host) 

	def ips(self):
		return {self.ip()}

	def host(self):
		return self._host

	def port(self):
		return self._port

	def login(self):
		return self._login

	def password(self):
		return self._password

	def get_subscription_node(self):
		return self._panel_server

	def get_session_file_path(self, filename):
		return self.get_subscription_node().get_session_file_path(filename)

	def session_dir(self):
		return self.get_subscription_node().session_dir()

	@property
	def mysql_bin(self):
		if not self.is_windows():
			return 'mysql'
		else:
			return ntpath.join(
				self._panel_server.plesk_dir, "MySQL\\bin\\mysql"
			)

	@property
	def plesk_dir(self):
		return self._panel_server.plesk_dir

	def __hash__(self):
		return hash((self.host(), self.port()))

	def __eq__(self, another): 
		return (
			isinstance(another, PleskDatabaseTargetServer) and
			another.host() == self.host() and another.port() == self.port() and
			another.get_subscription_node() == self.get_subscription_node()
		)