from parallels.ppa.source.helm4 import messages
import logging
import os
import xml.etree.ElementTree as et

from parallels.core.actions.hosting_settings.transfer_mime_types import TransferMIMETypesBase
from parallels.ppa.source.helm4 import helm_utils


logger = logging.getLogger(__name__)


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

		Returns dictionary {extension: mime type}
		"""
		domain_id = helm_utils.get_domain_id_by_name(
			global_context.conn, site.name
		)
		if domain_id is None:
			return None

		return self._get_mime_types(global_context, site.name, domain_id)

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

		Returns dictionary {
			virtual directory name: {
				extension: mime type
			}
		}
		"""
		domain_id = helm_utils.get_domain_id_by_name(global_context.conn, site.name)
		if domain_id is None:
			return None

		mime_types = self._get_mime_types(global_context, site.name, domain_id)
		if mime_types is None:
			return None

		vdirs_mime_types = {}
		vdirs = helm_utils.get_vdir_list(global_context.conn, site.name, domain_id)
		for vdir in vdirs:
			vdirs_mime_types[vdir.attrib['path']] = mime_types

		return vdirs_mime_types

	def _get_mime_types(self, global_context, site_name, domain_id):
		try:
			helm_config = global_context.conn.helm.conn_settings
			migration_tool_path = os.path.join(helm_config.migration_tool_dir, helm_config.migration_tool_name)

			with global_context.conn.helm.runner() as helm_runner:
				mime_types_xml = helm_runner.sh('{migration_tool_path} --mime-types {domain_id}',
						dict(migration_tool_path=migration_tool_path, domain_id=domain_id))
		except Exception as e:
			logger.debug(u'Exception:', exc_info=e)
			logger.error(messages.CANNOT_GET_MIME_TYPES_FOR_DOMAIN % (site_name, e))
			return None

		mime_types_xml = et.fromstring(mime_types_xml).findall('.//mimetype')

		if not mime_types_xml:
			return None

		mime_types = {}
		for mime_type in mime_types_xml:
			# minus the standard auto-generated types
			if mime_type.attrib['mimetype'] not in ['Reserved', 'Perl', 'Executable'] and not (mime_type.attrib['extension'] == '.phps' and 'application/x-httpd-php-source'):
				mime_types[mime_type.attrib['extension']] =  mime_type.attrib['mimetype']

		return mime_types
