from plone import api
from ploneintranet.core import _
from ploneintranet.layout.browser.base import BasePanel
from ploneintranet.workspace.basecontent.utils import dexterity_update
from zope.event import notify
from zope.lifecycleevent import ObjectModifiedEvent


class EditFolder(BasePanel):
    """
    Evaluate simple form and edit folder.
    """

    title = _("label_edit_folder_properties", default="Edit folder properties")
    panel_size = "medium"
    _form_data_pat_inject_parts = (
        "source: #workspace-documents; target: #workspace-documents",
        "source: nav.breadcrumbs; target: nav.breadcrumbs",
    )

    can_edit = True  # Protected in zcml

    def __call__(self, title=None, description=None):
        """Evaluate form and redirect"""
        if title is not None or description is not None:
            url = self.edit()
            return self.redirect(url)
        return self.index()

    def edit(self):
        """
        Edit content and return url. Uses dexterity_update to set the
        appropriate fields after creation.
        """
        modified, errors = dexterity_update(self.context, self.request)
        if modified and not errors:
            api.portal.show_message(
                _("Item edited."), request=self.request, type="success"
            )
            notify(ObjectModifiedEvent(self.context))

        if errors:
            for error in errors:
                api.portal.show_message(error, request=self.request, type="error")

        return self.context.absolute_url()

    def redirect(self, url):
        """
        Has its own method to allow overriding
        """
        url = f"{url}/view"
        return self.request.response.redirect(url)


class PanelRename(BasePanel):

    title = _("Rename")
    panel_size = "small"

    _form_data_pat_inject_parts = (
        "#global-statusmessage; loading-class: ''",
        "#workspace-documents",
        "#document-body",
    )

    def __call__(self):
        """Check if the document should be updated and update it
        (i.e. the form was submitted).
        To do that we reuse the logic contained in the default view.
        """
        view = api.content.get_view(
            self.context.getDefaultLayout(), self.context, self.request
        )
        if view.should_update():
            view.update()
            return self.request.RESPONSE.redirect(
                f"{self.context.absolute_url()}/view?show_sidebar=1"
            )
        return super().__call__()
