from parallels.core.actions.hosting_settings.transfer_mime_types import TransferMIMETypesBase
from parallels.core.utils import plesk_utils
from parallels.core.utils.restore_hosting_utils import restore_hosting_settings_lock
from parallels.plesk.source.plesk.plesk_utils import get_vdirs_list, source_websrvmng_lock
from parallels.core.utils.common import merge_dicts


class TransferMIMETypes(TransferMIMETypesBase):
	def _get_site_mime_types(self, global_context, subscription, site):
		"""Get MIME types of a site

		Override in child classes.

		Returns dictionary with keys - extensions, values - corresponding MIME types.
		If there are no MIME types for a site - returns None (default behavior)

		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		with restore_hosting_settings_lock:
			target_mime_types = plesk_utils.get_mime_types(
				subscription.web_target_server, site.name
			)

		with source_websrvmng_lock:
			source_mime_types = plesk_utils.get_mime_types(
				subscription.web_source_server, site.name
			)

		# On IIS 6 used by Plesk on windows 2003 no MIME types mean that HTML
		# pages are processed correctly, while on Plesk and IIS 7 that means
		# that HTML pages are not processed - you have to explicitly specify
		# MIME type for HTML pages. So we merge source and target MIME types,
		# source MIME types take priority, but default Plesk MIME types are
		# still present.
		return merge_dicts(target_mime_types, source_mime_types)

	def _get_site_vdir_mime_types(self, global_context, subscription, site):
		"""Get MIME types of all virtual directories inside a site

		Override in child classes.

		Returns dictionary with:
		- key - virtual directory path (as it is presented on target server)
		- value - dictionary with:
			- key - extensions
			- values - corresponding MIME types
		If there are no virtual directories with MIME types - returns None (default behavior)

		The dictionary looks in the following way:
		{
			virtual directory name: {
				extension: mime type
			}
		}

		:type global_context: parallels.core.global_context.GlobalMigrationContext
		:type subscription: parallels.core.migrated_subscription.MigratedSubscription
		"""
		vdirs_list = get_vdirs_list(global_context, subscription, site)
		with restore_hosting_settings_lock:
			target_mime_types = plesk_utils.get_mime_types(subscription.web_target_server, site.name)

		mime_types = {}
		for vdir in vdirs_list:
			with source_websrvmng_lock:
				source_mime_types = plesk_utils.get_mime_types(subscription.web_source_server, site.name, vdir)
			mime_types[vdir] = merge_dicts(target_mime_types, source_mime_types)

		return mime_types