from plone import api
from ploneintranet.workspace.config import TEMPLATES_FOLDER
from Products.PlonePAS.setuphandlers import activatePluginInterfaces
from Products.PluggableAuthService.interfaces.plugins import IGroupsPlugin


def post_install(context):
    """
    - adds the global "workspaces" container
    - adds the global "templates" case templates container
      (actual case template is provided by ploneintranet.suite)
    - makes sure the membrane groups plugin is ordered before the recursive
      groups plugin
    - sets the addable types for the ploneintranet policy
    """
    portal = api.portal.get()

    if "workspaces" not in portal:
        api.content.create(
            container=portal,
            id="workspaces",
            type="ploneintranet.workspace.workspacecontainer",
            title="Workspaces",
        )
    if TEMPLATES_FOLDER not in portal:
        api.content.create(
            container=portal,
            id=TEMPLATES_FOLDER,
            type="ploneintranet.workspace.workspacecontainer",
            title="Templates",
        )

    # deactivate the enumerate groups interface for collective.workspace
    activatePluginInterfaces(
        portal, "workspace_groups", disable=["IGroupEnumerationPlugin"]
    )

    au = api.portal.get_tool("acl_users")
    banned_ids = ("recursive_groups", "membrane_groups", "workspace_groups")
    for banned_id in banned_ids:
        try:
            au.plugins.deactivatePlugin(IGroupsPlugin, banned_id)
        except KeyError:
            pass  # Already deactivated

    # Set up the ploneintranet policy for all addable types
    # Re-run ploneintranet.workspace:default after installing extra types!
    default_types = []
    types = api.portal.get_tool("portal_types")
    for type_info in types.listTypeInfo():
        if type_info.global_allow:
            default_types.append(type_info.getId())

    if default_types:
        types_with_special_workflow = ("Folder", "todo", "Event")
        default_types = [
            x for x in default_types if x not in types_with_special_workflow
        ]
        pwftool = api.portal.get_tool("portal_placeful_workflow")
        policy = pwftool["ploneintranet_policy"]

        policy.setChainForPortalTypes(default_types, ("(Default)",))
