from plone import api
from ploneintranet.core import _
from ploneintranet.network.behaviors.metadata import IDublinCore
from ploneintranet.workspace.browser.cart_actions.base import BaseCartView
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.event import notify
from zope.lifecycleevent import Attributes
from zope.lifecycleevent import ObjectModifiedEvent

import logging

log = logging.getLogger(__name__)


class RenameView(BaseCartView):
    title = _("Batch rename")

    def confirm(self):
        index = ViewPageTemplateFile("templates/rename_confirmation.pt")
        return index(self)

    def rename(self):
        handled = []
        uids = self.request.form.get("uids", [])
        if uids:
            objs = [brain.getObject() for brain in api.content.find(UID=uids)]
        else:
            objs = []

        for obj in objs:
            new_title = self.request.form.get(obj.UID())
            if new_title:
                handled.append(f'"{obj.Title()}" → "{new_title}"')
                obj.title = new_title
                descriptions = [Attributes(IDublinCore, "title")]
                notify(ObjectModifiedEvent(obj, *descriptions))

        if handled:
            titles = ", ".join(sorted(handled))
            msg = _(
                "batch_rename_success",
                default="The following items have been renamed: ${title_elems}",
                mapping={"title_elems": titles},
            )
            api.portal.show_message(message=msg, request=self.request, type="success")
        else:
            api.portal.show_message(
                message=_("No items could be renamed"),
                request=self.request,
                type="info",
            )
        return self.redirect()
