from parallels.source.helm4 import messages
import logging
import os
from contextlib import closing
from xml.etree import ElementTree

from parallels.core.utils.windows_utils import convert_path

logger = logging.getLogger(__name__)


def get_helm_vhost_dir(conn, subscription_name):
	with closing(conn.helm.db()) as cursor:
		cursor.execute(u"""SELECT PropertyValue FROM ServiceProperty
			JOIN [Service] on [Service].ServiceId = ServiceProperty.ServiceId
			JOIN OnlineService_Service on OnlineService_Service.ServiceId = [Service].ServiceId
			JOIN OnlineService on OnlineService.OnlineServiceId = OnlineService_Service.OnlineServiceId
			WHERE
				ProviderGuid IN ('62541890-8A7F-47B3-A099-ED7569347718', 'EF9200DF-2A17-4956-94D5-3B9911E19217')
				And PropertyName = 'PhysicalPath'
				AND OnlineService.Name = '%s'""" % subscription_name)

		if cursor.rowcount() == 0:
			return 'C:\\Domains'

		return cursor.fetchone()[0]



def get_domain_id_by_name(conn, site_name):
	with closing(conn.helm.db()) as cursor:
		cursor.execute(u"""SELECT OnlineServiceId FROM OnlineService
					WHERE Name = '%s'""" % site_name)
		if cursor.rowcount() == 0:
			return None

		return cursor.fetchone()[0]



def get_vdir_list(conn, domain_name, domain_id):
	try:
		helm_config = conn.helm.conn_settings
		migration_tool_path = os.path.join(helm_config.migration_tool_dir, helm_config.migration_tool_name)

		with conn.helm.runner() as helm_runner:
			vdirs_xml = helm_runner.sh('{migration_tool_path} --virtual-directories {domain_id}',
				dict(migration_tool_path=migration_tool_path, domain_id=domain_id))

		return ElementTree.fromstring(vdirs_xml).findall('.//virtualdirectory')
	except Exception as e:
		logger.debug(u'Exception:', exc_info=e)
		logger.error(messages.CANNOT_GET_VDIRS_FOR_DOMAIN % (domain_name, e))
		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_helm_vhost_dir(
			self.global_context.conn, subscription.name
		)
		return convert_path(subscription, path, vhost_source_dir)
