"""A Cart Action for deleting all items listed in cart."""

from plone import api
from ploneintranet import api as pi_api
from ploneintranet.core import _
from ploneintranet.workspace.browser.cart_actions.base import BaseCartView
from ploneintranet.workspace.interfaces import ITrashed
from Products.CMFCore.interfaces import IFolderish
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.interface import alsoProvides


class DeleteView(BaseCartView):
    title = _("Batch delete")
    checked_permission = "Delete objects"
    confirm_index = ViewPageTemplateFile("templates/delete_confirmation.pt")

    def confirm(self):
        return self.confirm_index(self)

    def recursively_mark_trashed(self, obj=None):
        """Mark obj as trashed and apply the same operation to all
        the contained objects
        """
        obj = obj or self.context
        if not ITrashed.providedBy(obj):
            alsoProvides(obj, ITrashed)
            obj.reindexObject()
        if not IFolderish.providedBy(obj):
            return
        list(map(self.recursively_mark_trashed, obj.listFolderContents()))

    def redirect_no_action(self):
        api.portal.show_message(
            message=_("No items could be moved to trash"),
            request=self.request,
            type="info",
        )
        return self.redirect()

    def delete(self):
        uids = self.request.form.get("uids", [])
        if not uids:
            return self.redirect_no_action()

        objs = [brain.getObject() for brain in api.content.find(UID=uids)]
        if not objs:
            return self.redirect_no_action()

        handled = []
        with pi_api.env.indexing_disabled(self.request):
            for obj in objs:
                handled.append('"%s"' % obj.Title())
                self.recursively_mark_trashed(obj)

        titles = ", ".join(sorted(handled))
        msg = _(
            "batch_delete_success",
            default=("The following items have been moved to trash: " "${title_elems}"),
            mapping={"title_elems": titles},
        )
        api.portal.show_message(message=msg, request=self.request, type="success")
        return self.redirect()
