from plone import api
from plone.memoize.view import memoize
from ploneintranet.core import _
from ploneintranet.layout.browser.base import BasePanel
from ploneintranet.layout.browser.base import BaseView


class AttachmentsSearch(BaseView):

    result_limit = 20
    portal_types = ["File", "Image"]

    @property
    @memoize
    def default_path(self):
        return "/".join(api.portal.get().workspaces.getPhysicalPath())

    @property
    @memoize
    def path_options(self):
        options = []
        view = api.content.get_view(
            self.context.defaultView(), self.context, self.request
        )
        if view.workspace:
            options.append(
                {
                    "label": _("Search in current workspace"),
                    "value": "/".join(view.workspace.getPhysicalPath()),
                }
            )
        options.append(
            {"label": _("Search in all workspaces"), "value": self.default_path}
        )
        requested_value = self.request.get("path") or options[0]["value"]
        for option in options:
            if option["value"] == requested_value:
                option["checked"] = "checked"
        return options

    @property
    @memoize
    def search_util(self):
        return api.content.get_view(
            "search", api.portal.get(), self.request
        ).search_util

    @property
    @memoize
    def results(self):
        """The list of results to be displayed in the attachment picker"""
        searchable_text = self.request.get("SearchableText", "")
        if len(searchable_text) <= 2:
            return []
        _filters = {
            "path": (self.request.get("path") or self.default_path),
            "portal_type": self.portal_types,
        }

        response = self.search_util.query(
            phrase=searchable_text,
            filters=_filters,
            step=self.result_limit + 1,
            sort="sortable_title",
        )
        return list(response)

    def display_length_warning(self):
        """Condition to display a notice if we have too many results"""
        return len(self.results) > self.result_limit


class RemoveAttachmentPanel(BasePanel):

    _form_data_pat_inject_parts = (
        "#global-statusmessage; loading-class: ''",
        "#attached-documents-attachments-2",
    )

    @property
    @memoize
    def form_action(self):
        """The handler for this form"""
        return self.context.absolute_url()
