from OFS.CopySupport import CopyError
from plone import api
from ploneintranet.core import _
from ploneintranet.workspace.browser.cart_actions.base import BaseCartView
from ZODB.POSException import ConflictError

import re


class PasteView(BaseCartView):
    def do_paste(self):
        """Try to paste the documents and report about success or failure
        using a status message
        """
        try:
            self.context.manage_pasteObjects(REQUEST=self.request)
        except CopyError as ce:
            if hasattr(ce, "message"):
                message = re.sub("<[^>]*>|\n", " ", ce.message)
                message = re.sub(r"\s{2,}", " ", message).strip()
            else:
                message = str(ce)
            api.portal.show_message(
                message=message, request=self.request, type="warning"
            )
        except ConflictError:
            api.portal.show_message(
                message=_("Error while pasting items"),
                request=self.request,
                type="error",
            )
        else:
            api.portal.show_message(
                message=_("Item(s) pasted"), request=self.request, type="success"
            )

    def __call__(self):
        self.do_paste()
        return self.index()
