from functools import cached_property
from logging import getLogger
from plone import api
from plone.namedfile.field import NamedBlobImage
from plone.supermodel import model
from ploneintranet import schema
from ploneintranet.core import _
from ploneintranet.imagebank.browser.base import ImageBankBaseView
from ploneintranet.layout.widgets.form import PIEditForm
from Products.CMFCore.permissions import AddPortalContent
from z3c.form import form

logger = getLogger(__name__)


class ImageBankFolderView(ImageBankBaseView):

    @cached_property
    def title(self):
        """This returns the title translated to the current language,
        if a matching message id is found, otherwise it returns the original title.
        """
        return api.content.translate(self.context.title, domain="ploneintranet")

    def can_upload(self) -> bool:
        """Check if we have the permission to upload to the current folder."""
        return api.user.has_permission(AddPortalContent, obj=self.context)

    @cached_property
    def base_query(self) -> dict:
        """Look for images within the current folder context."""
        return {
            "portal_type": "Image",
            "context": self.context,
            "sort_on": "created",
            "sort_order": "descending",
        }


class IImageBankFolderUploadSchema(model.Schema):

    images = schema.MultipleFileInput(
        title="Images",
        required=False,
        value_type=NamedBlobImage(),
        accept=["image/*"],
    )


class ImageBankFolderUploadForm(PIEditForm):

    ignoreContext = True
    label = _("Upload images")
    description = ""
    schema = IImageBankFolderUploadSchema

    def redirect(self, message=None, type="info"):
        if message is not None:
            api.portal.show_message(
                message=message,
                request=self.request,
                type=type,
            )
        target = f"{self.context.absolute_url()}/@@app-image-bank-collection"
        return self.request.response.redirect(target)

    @form.button.buttonAndHandler(_("Upload"), name="upload")
    def handle_save(self, action):
        data, errors = self.extractData()
        if errors:
            self.status = self.formErrorsMessage
            return self.redirect(message=self.formErrorsMessage, type="error")
        elif images := data.get("images"):
            images = data.get("images", [])
            for image in images:
                api.content.create(
                    container=self.context,
                    type="Image",
                    title=image.filename,
                    image=image,
                )
            return self.redirect(
                _(
                    "Successfully uploaded ${count} image(s).",
                    mapping={"count": len(images)},
                ),
                type="success",
            )
