from parallels.core.actions.hosting_settings.transfer_mime_types import TransferMIMETypesBase
from parallels.core.utils.plesk_utils import get_mime_types
from parallels.core.utils.restore_hosting_utils import restore_hosting_settings_lock
from parallels.core.utils.common import merge_dicts, find_first


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}

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

        # Information about MIME types is actually dumped to backup by Helm 3
        # agent, so we just read it from raw dump. Converted dump could not have this information -
        # MIME types are removed from backup to avoid their restoration by PMM.
        raw_site = find_first(subscription.raw_dump.iter_domains(), lambda domain: domain.name == site.name)
        if raw_site is None:
            return None

        source_mime_types = raw_site.mime_types

        # On IIS 6 used by Helm 3 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):
        # There are no MIME types for each virtual directory in Helm 3
        return None