from contextlib import closing

from parallels.common.actions.hosting_settings.transfer_mime_types import TransferMIMETypesBase
from parallels.hsphere_migrator import hsphere_utils


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
		"""
		with closing(global_context.conn.hsphere.db()) as cursor:
			vhost_id = hsphere_utils.get_iis_vhost_id(cursor, site.name)
			if vhost_id is None: # if domain has no IIS hosting, skip transfer of MIME types
				return None

			return self._get_mime_types(cursor, vhost_id)

	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

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

		If there are no virtual directories with MIME types - returns None (default behavior)

		:type global_context: parallels.common.global_context.GlobalMigrationContext
		:type subscription: parallels.common.migrated_subscription.MigratedSubscription
		"""
		with closing(global_context.conn.hsphere.db()) as cursor:
			vhost_id = hsphere_utils.get_iis_vhost_id(cursor, site.name)
			if vhost_id is None: # if domain has no IIS hosting, skip transfer of MIME types
				return None

			vdirs_mime_types = {}
			cursor.execute(u"""
				SELECT wd.id, wd.dirname
				FROM iis_web_dir wd
				JOIN parent_child pc ON pc.child_id = wd.id
				WHERE pc.parent_id = %s
			""" % vhost_id)
			for (vdir_id, vdir_name) in cursor.fetchall():
				vdirs_mime_types[vdir_name] = self._get_mime_types(cursor, vdir_id)

			return vdirs_mime_types

	@staticmethod
	def _get_mime_types(cursor, parent_id):
		"""Get MIME types for the specified parent.
		Parent can be either a virtual host or a virtual directory.
		"""
		cursor.execute(u"""
			SELECT im.ext, im.mime_type
			FROM iis_mime im
			JOIN parent_child pc_mime ON pc_mime.child_id = im.id AND pc_mime.child_type = 22	-- mimetype
			WHERE pc_mime.parent_id = %s
		""" % parent_id)
		return {
			ext: mime_type
			for (ext, mime_type) in cursor.fetchall()
			# minus the standard auto-generated types
			if mime_type not in ['Reserved', 'Perl', 'Executable']
			and not (ext == '.phps' and 'application/x-httpd-php-source')
		}