from parallels.common.utils import plesk_utils
from parallels.target_panel_plesk.import_api.import_api_base import \
	PleskBaseImportAPI
from parallels.common.import_api.utils import plesk_windows_change_sysuser_login
from parallels.common.import_api.utils import plesk_windows_get_dedicated_app_pool_user


class PleskWindowsImportAPI(PleskBaseImportAPI):
	def change_sysuser_login(self, subscription_name, sysuser_login):
		plesk_windows_change_sysuser_login(
			self.conn.plesk_server, subscription_name, sysuser_login
		)

	@staticmethod
	def repair_webspace_security(subscription):
		with subscription.panel_target_server.runner() as runner:
			for _ in xrange(2):
				# Call repair webspace security twice, because there are issues
				# when restoring permissions on subdomains when migrating from
				# Plesk 8. If you call the utility once, it could set invalid
				# permissions, which causes some subdomains to response with
				# 500 status code.
				runner.run(
					ur'%s\bin\repair' % subscription.panel_target_server.plesk_dir,
					[
						'--repair-webspace-security', 
						'-webspace-name', subscription.name_idn
					]
				)

	def update_webspace_subdomains_security_metadata_location(self, domain_name):
		with self.conn.main_node_runner() as main_node_runner:
			main_node_runner.run(
				ur'%s\bin\repair' % self.conn.plesk_server.plesk_dir, [
					'--update-webspace-subdomains-security-metadata-location',
					'-webspace-name', domain_name
				])

	@staticmethod
	def get_dedicated_app_pool_user(subscription):
		"""
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		return plesk_windows_get_dedicated_app_pool_user(subscription.panel_target_server, subscription.name)

	def refresh_node_components(self, node):
		plesk_utils.refresh_node_components(node)