from plone import api
from ploneintranet.layout.browser.base import BaseView
from ploneintranet.layout.interfaces import IDiazoNoTemplate
from Products.CMFCore.utils import getToolByName
from zope.deprecation import deprecate
from zope.interface import implementer

import logging

log = logging.getLogger(__name__)


@implementer(IDiazoNoTemplate)
class PersonalTools(BaseView):
    """Personal Tools and User Information"""

    def get_actions(self):
        """Get the available actions from portal_actions"""
        return self.context.restrictedTraverse("@@plone_context_state").actions(
            "user_additional"
        )

    def enable_password_reset(self):
        """Check if the password reset is allowed"""
        check_view = api.content.get_view(
            "verify_password_reset_allowed", self.context, self.request
        )
        return check_view.is_allowed()

    @deprecate(
        "The avatar edit is not available anymore in the personal tools menu "
        "since https://github.com/quaive/ploneintranet/pull/2019."
    )
    def display_change_personal_image(self):
        """if portrait is not listed in read_only_fields
        we do not display the form to change it
        """
        ro_fields = api.portal.get_registry_record(
            "ploneintranet.userprofile.read_only_fields", default=()
        )
        return "portrait" not in ro_fields

    def __call__(self, *args, **kw):
        self.request["disable_toolbar"] = True
        return super().__call__(*args, **kw)

    def userinfo(self):
        # BBB this probably is not used anymore
        portal_membership = getToolByName(self.context, "portal_membership")
        member = portal_membership.getAuthenticatedMember()
        return {
            "fullname": member.getProperty("fullname"),
            "email": member.getProperty("email"),
        }
