from parallels.common.actions.hosting_settings.transfer_mime_types import TransferMIMETypesBase
from parallels.common.utils import plesk_utils
from parallels.plesks_migrator.plesk_utils import get_vdirs_list
from parallels.utils 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.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		target_mime_types = plesk_utils.get_mime_types(
			subscription.web_target_server, site.name
		)

		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.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		vdirs_list = get_vdirs_list(global_context, subscription, site)
		target_mime_types = plesk_utils.get_mime_types(subscription.web_target_server, site.name)

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

		return mime_types