from collective.ftw.upgrade import UpgradeStep
from plone import api


class ConfigurableUserprofileTabs(UpgradeStep):
    """Configurable userprofile tabs."""

    def __call__(self):
        # 1) Install all the default tabs
        self.install_upgrade_profile()

        # 2) Hide those which are "hidden" via the registry
        banned_tabs = api.portal.get_registry_record(
            "ploneintranet.userprofile.userprofile_hidden_info", default=()
        )

        if "userprofile-follow*" in banned_tabs:
            banned_tabs += ("userprofile-followers", "userprofile-following")

        portal_actions = api.portal.get_tool("portal_actions")
        userprofile_tabs = portal_actions.get("userprofile_tabs")

        # Hide banned tabs
        for banned_tab in banned_tabs:
            tab = userprofile_tabs.get(banned_tab)
            if tab:
                tab.visible = False

        # 3) Clean up the registry
        portal_registry = api.portal.get_tool("portal_registry")
        if portal_registry.get("ploneintranet.userprofile.userprofile_hidden_info"):
            del portal_registry.records[
                "ploneintranet.userprofile.userprofile_hidden_info"
            ]
