from plone import api
from ploneintranet.activitystream.browser.statusupdate import StatusUpdateView
from ploneintranet.microblog.statusupdate import StatusUpdate
from urllib.parse import urlencode


class PostComments(StatusUpdateView):
    _batch_size = 3
    _next_url_template = "{portal_url}/@@post-comments/{su_id}?{qs}"

    @property
    def number_of_replies(self) -> int:
        return len(self.replies)

    @property
    def page_number(self) -> int:
        """Get current page number from the request"""
        try:
            page = int(self.request.form.get("page", 1))
        except ValueError:
            page = 1
        return page

    @property
    def currently_displayed_comments(self) -> int:
        """Return the number how comments that are displayed in the current page"""
        return min(self.page_number * self._batch_size, self.number_of_replies)

    @property
    def next_page_url(self) -> str | None:
        """Return the URL to get the next page of results.
        If there is no next page because we already displayed all the comments,
        return None
        """
        if self.currently_displayed_comments == self.number_of_replies:
            return

        params = {"page": self.page_number + 1}
        return self._next_url_template.format(
            portal_url=api.portal.get().absolute_url(),
            su_id=self.context.id,
            qs=urlencode(params),
        )

    @property
    def comments_in_current_page(self) -> list[StatusUpdate]:
        """We need to get the comments contained in the current page.
        This means we will slice the replies like this,
        because we are doing a reverse batching

        page 1 => replies[-N:]
        page 2 => replies[-2N:-N]
        ...
        """
        stop = self.number_of_replies - (self.page_number - 1) * self._batch_size
        start = -(self.page_number) * self._batch_size
        stop = start + self._batch_size
        if stop >= 0:
            stop = None
        return self.replies[slice(start, stop)]
