from copy import deepcopy
from plone import api
from plone.memoize.view import memoize_contextless
from plone.tiles import Tile
from ploneintranet import api as pi_api
from ploneintranet.contacts.interfaces import IImportantContact
from ploneintranet.core import _
from ploneintranet.search.interfaces import ISiteSearch
from zope.component import getUtility


class ContactsSearch(Tile):

    title = _("label_title_app_contacts", default="Contacts")
    _tabs = [
        {"title": _("Important"), "id": "important"},
        {"title": _("Recently visited"), "id": "recent"},
        {"title": _("Bookmarked"), "id": "bookmarked"},
    ]

    @property
    def default_tabid(self):
        return "important" if self.important_contacts() else "recent"

    def tabs(self):
        """Return the tabs with the proper current class"""
        tabs = deepcopy(self._tabs)
        if not self.important_contacts():
            # Don't show if not important contacts are defined.
            tabs = [it for it in tabs if it["id"] != "important"]
        tabid = self.current_tabid
        for tab in tabs:
            tab["current"] = "current" if tab["id"] == tabid else ""
        return tabs

    @property
    @memoize_contextless
    def has_searched(self):
        """Check if the user has searched"""
        return bool(self.request.get("SearchableText"))

    @property
    @memoize_contextless
    def current_tabid(self):
        """Check the current tab_id"""
        current = self.request.get("tabid") or self.default_tabid
        if current == "important" and not self.important_contacts():
            # fall back to default if "important" is requested but no
            # important contacts available
            current = self.default_tabid
        return current

    @property
    @memoize_contextless
    def app_tile(self):
        portal = api.portal.get()
        apps = portal.get("apps", {})
        app = apps.get("contacts")
        if not app:
            return
        return api.content.get_view("app-tile", app, self.request)

    def header_link(self):
        """Link to the Contacts app (if it is available)"""
        tile = self.app_tile
        if not tile or tile.disabled:
            return ""
        return tile.url

    def is_show_important_contacts(self):
        if not self.important_contacts():
            # Don't show if not important contacts are defined.
            return False
        return self.current_tabid == "important"

    def is_show_recent_contacts(self):
        if not api.portal.get_registry_record(
            "ploneintranet.userprofile.portlet_contacts_recent"
        ):
            return False
        return self.current_tabid == "recent"

    def is_show_bookmarked_contacts(self):
        return self.current_tabid == "bookmarked"

    @memoize_contextless
    def important_contacts(self):
        search = getUtility(ISiteSearch)
        filters = {
            "portal_type": [
                "ploneintranet.contacts.contact",
            ],
            "object_provides": IImportantContact.__identifier__,
        }

        response = search.query(
            filters=filters,
            start=0,
            step=999999,
        )

        ret = []
        for it in response:
            ob = it.getObject()
            ret.append(
                {
                    "avatar_alt": _(
                        "contacts_portlet__avatar_alt",
                        default="Image of ${name}",
                        mapping={"name": it.title},
                    ),
                    "avatar_img": None,  # TODO: not implemented yet
                    "icon": f"icon-{ob.service_icon}" if ob.service_icon else "",
                    "initials": ob.initials,
                    "name": ob.fullname,
                    "title": it.title,
                    "url": it.url,
                }
            )
        return ret

    def recent_contacts(self):
        profile = pi_api.userprofile.get_current()
        if profile is not None and profile.recent_contacts:
            recent = [pi_api.userprofile.get(user) for user in profile.recent_contacts]
            recent = [p for p in recent if p][:10]
            return recent
        return []

    def bookmarked_users(self):
        """Retrieve my bookmarked contacts using the bookmark app"""
        view = api.content.get_view(
            "app-bookmarks", self.context.apps.bookmarks, self.request
        )
        return view.my_bookmarked_people()

    @memoize_contextless
    def get_byline_fieldname(self):
        portlet_contacts_byline_field = api.portal.get_registry_record(
            "ploneintranet.userprofile.portlet_contacts_byline_field",
            default="contact_telephone",
        )
        return portlet_contacts_byline_field
