from datetime import datetime
from io import BytesIO
from plone import api
from ploneintranet.core import _
from Products.Five.browser import BrowserView

import logging
import zipfile

logger = logging.getLogger(__name__)


class DownloadFiles(BrowserView):
    @property
    def payload(self):
        files = api.content.find(context=self.context, portal_type="File")
        documents = api.content.find(context=self.context, portal_type="Document")
        if not files and not documents:
            api.portal.show_message(_("No items found!"))
            return self.request.response.redirect(self.context.absolute_url())

        output = BytesIO()
        with zipfile.ZipFile(output, mode="w") as zf:
            path_cutoff = len(self.context.getPhysicalPath())
            for file in files:
                obj = file.getObject()
                if not obj.file:
                    continue
                filename = obj.file.filename
                base_path = obj.getPhysicalPath()[path_cutoff:-1]
                path = "/".join(base_path + (filename,))
                zf.writestr(path, obj.file.data)
            for document in documents:
                obj = document.getObject()
                filename = f"{obj.getId()}.html"
                base_path = obj.getPhysicalPath()[path_cutoff:-1]
                path = "/".join(base_path + (filename,))
                zf.writestr(path, obj.text.output)

        return output.getvalue()

    def __call__(self):
        now = datetime.now().strftime("%Y-%m-%dT%H:%M:%S")
        zipfilename = f"download-{now}.zip"
        self.request.response.setHeader("Content-Type", "application/zip")
        self.request.response.setHeader(
            "Content-Disposition", f"attachment; filename={zipfilename}"
        )
        return self.payload
