from contextlib import closing

from parallels.core.utils.windows_utils import convert_path
from parallels.core.utils.windows_utils import path_join as windows_path_join


def get_site_vhost_settings(cursor, site_name):
	"""Return physical settings of the specified site:
	(vhost_id, sysuser_name, parent_dir)
	"""
	# l_server_id, vhost_id, domain_type, domain_id
	cursor.execute(u"""
		SELECT
			iis_vhost.host_id, iis_vhost.id, pc_iis.parent_type, pc_iis.parent_id
		FROM domains
			JOIN parent_child pc_iis ON pc_iis.parent_id = domains.id AND pc_iis.child_type = 9	-- Hosting
			JOIN iis_vhost ON iis_vhost.id = pc_iis.child_id
		WHERE
			pc_iis.parent_type IN (2, 31, 34, 35)
			AND domains.name = '%s'
	""" % site_name)
	row = cursor.fetchone()
	if row is None:  # if domain has no IIS hosting, skip transfer of virtual directories
		return None
	(l_server_id, vhost_id, domain_type, domain_id) = row

	# sysuser_name
	# path is: subdomain_tier2 -> subdomain_tier1 -> domain -> unix_user
	while domain_type == 31:
		cursor.execute(u"SELECT parent_id, parent_type FROM parent_child WHERE child_id = %s" % domain_id)
		(domain_id, domain_type) = cursor.fetchone()

	cursor.execute(u"""
		SELECT uu.login
		FROM unix_user uu
		JOIN parent_child pc_domain ON uu.id = pc_domain.parent_id
		WHERE pc_domain.child_id = %s
	""" % domain_id)
	(sysuser_name,) = cursor.fetchone()

	# vhosts_dir
	cursor.execute(u"""
		SELECT ppp.value
		FROM pserver_profile_params ppp
		JOIN pserver_to_profile ptp ON ptp.profile_id = ppp.profile_id
		JOIN l_server ls ON ls.p_server_id = ptp.ps_id
		WHERE ls.id = %s AND ppp.name = 'generalHosting_hshome'
	""" % l_server_id)
	vhosts_dir = cursor.fetchvalue() or r'c:\hshome'

	return vhost_id, sysuser_name, vhosts_dir


def get_iis_vhost_id(cursor, site_name):
	cursor.execute(u"""
		SELECT pc_iis.child_id
		FROM domains
		JOIN parent_child pc_iis ON pc_iis.parent_id = domains.id AND pc_iis.child_type = 9	-- Hosting
		WHERE pc_iis.parent_type IN (2, 31, 34, 35) AND domains.name = '%s'
	""" % site_name)
	row = cursor.fetchone()
	if row is None:
		return None
	else:
		return row[0]


def get_vhost_dir_source(global_context, site):
	"""Return vhost directory of the specified site on source server
	"""
	with closing(global_context.conn.hsphere.db()) as cursor:
		vhost_settings = get_site_vhost_settings(cursor, site.name)
	if vhost_settings is not None:
		(_, sysuser_name, vhosts_dir) = vhost_settings
		return windows_path_join(vhosts_dir, sysuser_name)
	else:
		return None


class PathConverter(object):
	def __init__(self, global_context):
		self.global_context = global_context

	def convert(self, subscription, site, path):
		vhost_source_dir = get_vhost_dir_source(self.global_context, site)
		return convert_path(subscription, path, vhost_source_dir)
