from itertools import islice
from ploneintranet import api as pi_api
from Products.Five import BrowserView

import json
import string


class GroupPicker(BrowserView):
    def _serve_json(self, data):
        """Serve the data as JSON, setting the proper response headers"""
        self.request.response.setHeader("Content-type", "application/json")
        return json.dumps(data)

    def __call__(self):
        """Return some json that is understood by the pat-autosuggest javascript"""
        query = self.request.get("q", "").strip(string.whitespace + "*")
        if not query:
            return self._serve_json({})

        try:
            limit = int(self.request.get("page_limit", 10))
        except ValueError:
            limit = 10

        groups = islice(
            pi_api.workgroup.get_groups(
                SearchableText=f"*{query}*",
                full_objects=False,
            ),
            limit,
        )

        limit = limit
        return self._serve_json(
            [{"id": group.getGroupId, "text": group.Title} for group in groups]
        )
