from plone.memoize.view import memoize
from ploneintranet.core import _
from ploneintranet.layout.browser.actions import PIDeleteConfirmationForm
from ploneintranet.workspace.utils import parent_workspace
from z3c.form import button


class TodoDeleteConfirmationForm(PIDeleteConfirmationForm):
    """Override the Delete confirmation view to redirect to the todo app
    if the task is in the userprofile context.

    Note: we need to override both the actions
    """

    @property
    @memoize
    def in_workspace(self):
        return not self.request.form.get("app") and parent_workspace(self.context)

    @property
    @memoize
    def form_data_pat_inject(self):
        """Re-inject the task sidebar, without the deleted item"""
        if self.in_workspace:
            return (
                "#global-statusmessage; loading-class: '' && #selector && "
                "#document-body && #workspace-tickets"
            )

    @button.buttonAndHandler(_("I am sure, delete now"), name="Delete")
    def handle_delete(self, action):
        base_handler = super().handle_delete
        base_handler(self, action)
        if self.in_workspace:
            return
        url = self.context.apps["todo"].app_url()
        return self.request.response.redirect(url)

    @button.buttonAndHandler(_("label_cancel", default="Cancel"), name="Cancel")
    def handle_cancel(self, action):
        return self.request.response.redirect(self.view_url())
