from AccessControl import ClassSecurityInfo
from AccessControl.class_init import InitializeClass
from plone import api
from Products.membrane.config import TOOLNAME
from Products.membrane.interfaces.plugins import IMembraneUserFactoryPlugin
from Products.membrane.plugins.userfactory import MembraneUser
from Products.membrane.plugins.userfactory import MembraneUserFactory
from Products.PageTemplates.PageTemplateFile import PageTemplateFile
from zope.interface import implementer

manage_addPIUserFactoryForm = PageTemplateFile(
    "www/PIUserFactoryForm", globals(), __name__="manage_addPIUserFactoryForm"
)


def addPIUserFactory(dispatcher, id, title=None, REQUEST=None):
    """Add a PIUserFactory to a Pluggable Auth Service."""

    pmm = PIUserFactory(id, title)
    dispatcher._setObject(pmm.getId(), pmm)

    if REQUEST is not None:
        REQUEST["RESPONSE"].redirect(
            "%s/manage_workspace"
            "?manage_tabs_message="
            "PIUserFactory+added." % dispatcher.absolute_url()
        )


@implementer(IMembraneUserFactoryPlugin)
class PIUserFactory(MembraneUserFactory):

    security = ClassSecurityInfo()
    meta_type = "PI User Factory"

    @security.private
    def createUser(self, user_id, name):
        mbtool = api.portal.get_tool(TOOLNAME)
        # don't create the user unless it's a membrane-based user
        if mbtool.getUserObject(user_id=user_id, brain=True) is None:
            return None
        if not mbtool.case_sensitive_auth:
            user_id = mbtool.getOriginalUserIdCase(user_id)
        return PIUser(user_id, name)


InitializeClass(PIUserFactory)

_marker = ["INVALID_VALUE"]


class PIUser(MembraneUser):

    security = ClassSecurityInfo()


InitializeClass(PIUser)
