from plone import api
from ploneintranet.core import _
from ploneintranet.workspace.browser.cart_actions.base import BaseCartView


class ArchiveView(BaseCartView):
    """Archive Action implementation that uses slc.outdated to mark items as
    archived.
    """

    def __call__(self):
        request = self.request

        pm = api.portal.get_tool("portal_membership")
        user = pm.getAuthenticatedMember()

        handled = []
        for obj in self.items:
            title = obj.Title()
            if not user.has_permission("Modify portal content", obj):
                api.portal.show_message(
                    f"Could not archive object '{title}': Permission denied",
                    request=request,
                    type="warning",
                )
                continue
            outdated_view = obj.restrictedTraverse("object_toggle_outdated")
            outdated_view.outdated = True
            obj.reindexObject()
            handled.append(title)

        titles = ", ".join(sorted(handled))
        message = _(
            "The following items have been archived: ${titles}",
            mapping={"titles": titles},
        )
        api.portal.show_message(message=message, request=request, type="success")

        return self.index()
