from plone import api
from plone.locking.browser.locking import LockingInformation
from plone.locking.browser.locking import LockingOperations
from plone.locking.interfaces import ILockable
from ploneintranet import api as pi_api
from ploneintranet.core import _
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile


class PILockingInformation(LockingInformation):
    """Locking informations for Plone Intranet"""

    panel_template = ViewPageTemplateFile("templates/locking_panel.pt")

    def chat_link(self):
        """If the user is a ploneintranet user profile,
        return a link to open a chat with him.
        """
        info = self.lock_info()
        if not info:
            return {}
        user = pi_api.userprofile.get(info.get("creator"))
        if not user:
            return {}
        portal = api.portal.get()
        try:
            app = portal.apps.messages
        except AttributeError:
            return {}

        app_tile = api.content.get_view("app-tile", app, self.request)
        if app_tile.disabled:
            return {}
        return {
            "url": "{app_url}/{userid}/#end-of-conversation".format(
                app_url=app_tile.url, userid=user.id
            ),
            "label": _(
                "lock_panel_chat_link_label",
                default=("Chat with ${fullname}."),
                mapping={"fullname": user.fullname or user.id},
            ),
        }

    def render_panel(self):
        """Render the locking panel"""
        return self.panel_template()


class PILockingOperations(LockingOperations):
    """Customize the locking operations"""

    def force_unlock(self, redirect=True):
        """Steal the lock.

        If redirect is True, redirect back to the context URL, i.e. reload
        the page showing the sidebar
        """
        lockable = ILockable(self.context)
        lockable.unlock()
        if not redirect:
            return
        # The Ploneintranet customization consists in adding
        # the request parameter show_sidebar=1 to the URL
        url = self.context.absolute_url()
        types_use_view = api.portal.get_registry_record(
            "plone.types_use_view_action_in_listings", default=[]
        )
        if self.context.portal_type in types_use_view:
            url += "/view"
        url += "?show_sidebar=1"
        self.request.RESPONSE.redirect(url)
