from plone import api
from ploneintranet import api as pi_api
from ploneintranet.core import _
from ploneintranet.layout.browser.base import BasePanel
from ploneintranet.layout.browser.base import BaseView
from ploneintranet.workspace.interfaces import ITrashed
from zope.i18n import translate
from zope.interface import noLongerProvides


class EmptyTrashPanel(BasePanel):
    title = _("Empty trash")
    can_edit = True
    _form_data_pat_inject_parts = (
        "#selector",
        "#global-statusmessage; loading-class: ''",
    )

    def remove_forever(self):
        """Delete all the items the user can delete from the trash bin"""
        brains = api.content.find(context=self.context, trashed=True)
        objs = [brain.getObject() for brain in brains]
        failed = []
        for obj in objs:
            try:
                api.content.delete(obj=obj, check_linkintegrity=False)
            except Exception as e:
                failed.append((obj, e))
        if not failed:
            api.portal.show_message(
                message=_("The trash can is empty"),
                type="success",
                request=self.request,
            )
        else:
            msg = translate(
                _(
                    "empty_trash_error",
                    default=(
                        "One or more objects could not be removed from trash: ${objects}"  # noqa: E501
                    ),
                    mapping={
                        "objects": ", ".join(
                            [
                                "{title} ({err})".format(
                                    title=obj.Title(),
                                    err=err,
                                )
                                for obj, err in failed
                            ]
                        )
                    },
                ),
                target_language=api.portal.get_current_language(),
            )
            api.portal.show_message(message=msg, type="error", request=self.request)

    def __call__(self):
        if self.is_posting():
            with pi_api.env.indexing_disabled(self.request):
                self.remove_forever()
            target = f"{self.context.absolute_url()}/@@sidebar.trash"
            return self.request.response.redirect(target)
        return super().__call__()


class UntrashView(BaseView):
    """Untrash the context and return its view"""

    def do_untrash(self):
        """Untrash the trashed objects and all its parents"""
        objs = [obj for obj in self.context.aq_chain if ITrashed.providedBy(obj)]
        for obj in objs:
            noLongerProvides(obj, ITrashed)
            obj.reindexObject()

        if objs:
            msg = _("Document recovered successfully")
            msg_type = "success"
        else:
            msg = _("The document does not appear to be in the trash can." " Aborting.")
            msg_type = "warning"
        api.portal.show_message(message=msg, request=self.request, type=msg_type)

    def __call__(self):
        """Untrash the context and redirect to its view"""
        self.do_untrash()
        return self.request.response.redirect(
            f"{self.context.absolute_url()}/view?show_sidebar=1"
        )
