from plone.memoize.view import memoize_contextless
from ploneintranet.layout.interfaces import IDiazoAppTemplate
from ploneintranet.search.interfaces import ISiteSearch
from Products.Five import BrowserView
from urllib.parse import urlencode
from zope.component import getUtility
from zope.interface import implementer


@implementer(IDiazoAppTemplate)
class WorkGroupContainerView(BrowserView):
    """The view for the workgroup contrainer"""

    solr_step = 6

    @property
    @memoize_contextless
    def page_idx(self):
        return int(self.request.form.get("page_idx", 0))

    @property
    @memoize_contextless
    def page_size(self):
        return int(self.request.form.get("page_size", self.solr_step))

    @property
    @memoize_contextless
    def query_more(self):
        if not len(self.groups()) == self.page_size:
            return ""
        params = self.request.form.copy()
        params["page_idx"] = self.page_idx + 1
        return urlencode(params, doseq=True)

    @memoize_contextless
    def groups(self):
        """(first) page of matching users"""
        search = getUtility(ISiteSearch)
        filters = {
            "portal_type": "ploneintranet.userprofile.workgroup",
            "review_state": "enabled",
        }
        start = self.page_idx * self.page_size
        step = self.page_size
        response = search.query(
            filters=filters, sort="sortable_title", start=start, step=step
        )
        return tuple(response)
