from plone import api
from plone.app.layout.viewlets import common
from plone.memoize.view import memoize
from plone.registry.interfaces import IRegistry
from Products.Five.browser.pagetemplatefile import ViewPageTemplateFile
from zope.component import getUtility


class GlobalSectionsViewlet(common.GlobalSectionsViewlet):
    def update(self):
        super().update()

    def get_key(self, key):
        registry = getUtility(IRegistry)
        return registry.get(key, None)

    @property
    @memoize
    def portal_tabs(self):
        """Disable 'news' and 'library' for extranet users"""
        if not api.portal.get_registry_record(
            "ploneintranet.userprofile.extranet_enabled", default=False
        ):
            return super().portal_tabs

        if api.user.is_anonymous():
            return []
        portal = api.portal.get()
        user = api.user.get_current()
        return [
            tab
            for tab in super().portal_tabs
            # this also matches if there is no portal.tabid context object
            # i.e. dashboard.html
            if api.user.has_permission("View", user=user, obj=portal.get(tab.get("id")))
        ]

    @property
    @memoize
    def selected_portal_tab(self):
        """Port from plone.app.layout code that has been deprecated
        because Plone now marks the current selected tab client side

        See:
        - https://github.com/plone/plone.app.layout/pull/231
        - https://github.com/plone/plone.app.layout/pull/240

        TODO: this method should be removed and we should switch to marking
        the portal tab client side as well
        """
        portal = api.portal.get()
        plone_url = portal.absolute_url()
        plone_url_len = len(plone_url)
        request = self.request
        valid_actions = []

        url = request["URL"]
        path = url[plone_url_len:]
        path_list = path.split("/")
        if len(path_list) <= 1:
            return "index_html"

        # do not consider external links
        actions = (
            action for action in self.portal_tabs if action["url"].startswith(plone_url)
        )
        for action in actions:
            action_path = action["url"][plone_url_len:]
            if not action_path.startswith("/"):
                action_path = "/" + action_path
            action_path_list = action_path.split("/")
            if action_path_list[1] == path_list[1]:
                # Make a list of the action ids, along with the path length
                # for choosing the longest (most relevant) path.
                valid_actions.append((len(action_path_list), action["id"]))

        # Sort by path length, the longest matching path wins
        valid_actions.sort()
        if valid_actions:
            return valid_actions[-1][1]
        return "index_html"


class LogoViewlet(common.LogoViewlet):

    index = ViewPageTemplateFile("logo.pt")


class PIPathBarViewlet(common.PathBarViewlet):

    index = ViewPageTemplateFile("templates/path_bar.pt")
