from plone.memoize.view import memoize
from plone.rfc822.interfaces import IPrimaryFieldInfo
from ploneintranet.workspace.utils import map_content_type


class DownloadAsMixin:
    """Mixin class that provides a couple of methods to build the
    "Download as $TYPE" links
    """

    @property
    @memoize
    def _download_content_type(self):
        """Check this context and analyze the content of the primary field"""
        try:
            primary_field_info = IPrimaryFieldInfo(self.context)
        except TypeError:
            return ""
        if not hasattr(primary_field_info.value, "contentType"):
            return ""
        return primary_field_info.value.contentType

    def icon_class(self):
        """Gets the icon class for the primary field of this content"""
        contenttype = self._download_content_type
        if contenttype:
            icon_name = map_content_type(contenttype)
            if icon_name:
                return f"icon-file-{icon_name}"
        return "icon-file-code"

    @property
    def content_type_name(self):
        """Gets a name for the type of the primary field of this content"""
        contenttype = self._download_content_type
        name = ""
        if contenttype:
            name = map_content_type(contenttype)
        if name.lower() == "pdf":
            return "PDF"
        if name:
            return name.capitalize()
        return "unknown"
