from plone import api
from plone.memoize.view import memoize_contextless
from plone.tiles import Tile
from ploneintranet.layout.interfaces import IAppContainer
from ploneintranet.news.content import NEWS_SECTION_TYPES
from Products.CMFCore.interfaces import ISiteRoot

import datetime


class SidebarTile(Tile):
    @property
    @memoize_contextless
    def app(self):
        if IAppContainer.providedBy(self.context):
            return self.context
        for item in self.context.aq_chain:
            if IAppContainer.providedBy(item):
                return item
            elif ISiteRoot.providedBy(item):
                return None

    @memoize_contextless
    def sections(self):
        sections = self.app.listFolderContents({"portal_type": NEWS_SECTION_TYPES})
        return sorted(sections, key=lambda section: section.title)

    @property
    @memoize_contextless
    def publisher_view(self):
        """Return the publisher view in the context of the app"""
        return api.content.get_view("publisher", self.app, self.request)

    @property
    @memoize_contextless
    def now(self):
        return datetime.datetime.now(datetime.UTC)

    @memoize_contextless
    def show_add_button(self):
        """Check if the user can add sections to the news publishers or news
        to at least one section
        """
        if api.user.has_permission("Add portal content", obj=self.app):
            return True
        return bool(self.publisher_view.get_target_sections())

    @memoize_contextless
    def edit_app_link(self):
        """Check if the user is allowed to edit the app, and if yes, return the link
        for editiing it."""
        if api.user.has_permission("Modify portal content", obj=self.app):
            return "{app}/panel-edit-frontpage.html#document-content".format(
                app=self.app.absolute_url()
            )

    @memoize_contextless
    def normalise_id(self, _id):
        return _id.replace(".", "-")
