from plone import api
from plone.app.contenttypes.interfaces import IFile
from plone.indexer import indexer
from plone.rfc822.interfaces import IPrimaryFieldInfo
from Products.CMFCore.interfaces import IContentish
from Products.MimetypesRegistry import MimeTypeException
from zope.interface.interfaces import ComponentLookupError

import logging

logger = logging.getLogger(__name__)


def guess_mimetype_name(obj):
    """Guess the proper mime type name for an object
    as defined in the mimetype registry.
    Returns an empty string if no suitable name can be found
    """
    # If the object is a file get the friendly name of the mime type
    if not IFile.providedBy(obj):
        return ""

    try:
        mtr = api.portal.get_tool(name="mimetypes_registry")
        primary_field_info = IPrimaryFieldInfo(obj)
        contenttype = primary_field_info.value.contentType
        for result in mtr.lookup(contenttype):
            name = result.name()
            if name != contenttype:
                return name
    except (AttributeError, api.exc.CannotGetPortalError):
        return ""
    except MimeTypeException as error:
        logger.warning(
            "mimetype lookup failed for %s. Error: %s", obj.absolute_url(), error
        )
        return ""


@indexer(IContentish)
def friendly_type_name(obj):
    """Index for the friendly name of any content type.
    The name can be customized using the registry record
    ploneintranet.layout.mimetype_name2friendly_type_name

    :param obj: The Plone content object to index
    :type obj: IContentish
    :return: Friendly content type name
    :rtype: str
    """
    name = guess_mimetype_name(obj) or obj.Type()
    try:
        mapping = api.portal.get_registry_record(
            "ploneintranet.search.friendly_type_name_mapping", default={}
        )
    except ComponentLookupError:
        # happens during tests
        mapping = {}
    return mapping.get(name, name)
