from plone import api
from ploneintranet.core import _
from Products.CMFEditions.interfaces.IArchivist import ArchivistRetrieveError
from Products.Five import BrowserView


class DownloadFileVersion(BrowserView):
    """Helper method replacing the file_download_version skin script of
    CMFEditions modified to work with Dexterity Blob file types
    """

    def get_version_object(self, version_id):
        """Look up the given revision for this context.
        If not found return None
        """
        pr = api.portal.get_tool("portal_repository")
        try:
            version = pr.retrieve(self.context, version_id)
        except ArchivistRetrieveError:
            return
        return version.object

    def warn_and_redirect(self):
        msg = _("No file to download for this version")
        api.portal.show_message(message=msg, request=self.request, type="error")
        context_state = api.content.get_view(
            "plone_context_state", self.context, self.request
        )
        target = context_state.view_url()
        return self.request.response.redirect(target)

    def __call__(self, version_id=1):
        obj = self.get_version_object(version_id)
        file_field = obj and obj.file
        if file_field is None:
            return self.warn_and_redirect()

        setHeader = self.request.RESPONSE.setHeader
        setHeader("Content-Type", file_field.contentType)
        setHeader("Content-Length", file_field.getSize())
        setHeader(
            "Content-Disposition",
            'attachment;filename="%s"' % file_field.filename,
        )
        return file_field.data
