######################################################################
#
# utils 	Utility functions for the JTracker product
#
# This software is governed by a license. See 
# LICENSE.txt for the terms of this license.
#
######################################################################
__version__='$Revision: 1.13 $'[11:-2]

from Acquisition import aq_base

try:
    from Products.ZCTextIndex.ZCTextIndex import PLexicon
    from Products.ZCTextIndex.Lexicon import Splitter, CaseNormalizer
    from Products.ZCTextIndex.Lexicon import StopWordRemover
    have_zctextindex = 1
except ImportError:
    have_zctextindex = 0

from Permissions import SubmitJTrackerIssues, SupportJTrackerIssues
import AccessControl, Products, Globals


class TextIndexExtra:
    def __init__(self, lexicon_id, index_type):
        self.lexicon_id = lexicon_id
        self.index_type = index_type


def setupCatalog(container):
    """ Helper to set up the ZCatalog """
    if hasattr(aq_base(container), 'catalog'):
        return

    container.manage_addProduct['ZCatalog'].manage_addZCatalog( 'catalog'
                                                              , 'Catalog'
                                                              )
    cat = getattr(container, 'catalog')

    if have_zctextindex:
        # ZCTextIndex lexicon
        lexicon = PLexicon( 'lexicon'
                          , 'Lexicon'
                          , Splitter()
                          , CaseNormalizer()
                          , StopWordRemover()
                          )
        cat._setObject('lexicon', lexicon)

        # Adding indices
        ti_extra = TextIndexExtra('lexicon', 'Okapi BM25 Rank')
        cat.addIndex('SearchableText', 'ZCTextIndex', ti_extra)
    else:
        cat.addIndex('SearchableText', 'TextIndex')

    FIELDS = ( 'id'
             , 'requester_name'
             , 'stage'
             , 'component'
             , 'request_type'
             )

    for name in FIELDS:
        try:
            cat.addIndex(name, 'FieldIndex')
        except:
            pass

    # Adding metadata columns
    for name in ( 'id', 'title', 'description', 'stage', 'requester_name'
                , 'date', 'followups', 'component', 'request_type'
                , 'meta_type'
                ):
        try:
            cat.addColumn(name)
        except:
            pass


def registerPermission(permission, roles):
    """Make sure that a permission is registered with the given roles."""
    registered = AccessControl.Permission._registeredPermissions
    if not registered.has_key(permission):
        registered[permission] = 1
        Products.__ac_permissions__=(
            Products.__ac_permissions__+((permission,(),roles),))
        mangled = AccessControl.Permission.pname(permission)
        setattr(Globals.ApplicationDefaultPermissions, mangled, roles)


def initializeSecurity(jtracker):
    """ Do all the security settings we need """
    AllRoles = ('JTracker Supporter',)

    for role in AllRoles:
        if not jtracker._has_user_defined_role(role):
            jtracker._addRole(role)

    
    def setDefaultRoles(permission, roles, object=jtracker):
        registerPermission(permission, roles)

        # Get the current roles with the given permission, so
        # that we don't overwrite them. We basically need to
        # merge the current roles with the new roles to be
        # assigned the given permission.
        current = object.rolesOfPermission(permission)
        roles = list(roles)
        for dict in current:
            if dict.get('selected'):
                roles.append(dict['name'])
        object.manage_permission(permission, roles, 1)

    # Give all roles the permissions that Anonymous would get.
    setDefaultRoles(AccessControl.Permissions.access_contents_information,
                    AllRoles
                    )
    setDefaultRoles(AccessControl.Permissions.view,
                    AllRoles
                    )
    setDefaultRoles(AccessControl.Permissions.search_zcatalog,
                    AllRoles
                    )
    setDefaultRoles(AccessControl.Permissions.query_vocabulary,
                    AllRoles
                    )
    setDefaultRoles(AccessControl.Permissions.use_database_methods,
                    AllRoles
                    )

    setDefaultRoles('Access Transient Objects', AllRoles)
    setDefaultRoles('Access session data', AllRoles)
 
    setDefaultRoles(SupportJTrackerIssues, ('JTracker Supporter',))
    setDefaultRoles(SubmitJTrackerIssues, AllRoles)

NEW_ISSUE_TEMPLATE = """New issue by %(requester_name)s (%(requester_email)s):

"%(title)s"
%(request_url)s

----------

%(description)s

----------

Sent automatically by JTracker "%(jtracker_title)s" at %(jtracker_url)s
"""

REPLY_TEMPLATE = """Issue followup (%(request_type)s) \
by %(requester_name)s (%(requester_email)s):

"%(title)s"
%(request_url)s

----------

%(description)s

----------

Sent automatically by JTracker "%(jtracker_title)s" at %(jtracker_url)s
"""

MAIL_ERROR_TEMPLATE = """Fatal mail errors receiving mail from \
%(requester_name)s (%(requester_email)s):

Subject: %(subject)s

%(errors)s

----------

%(description)s

----------

Sent automatically by JTracker "%(jtracker_title)s" at %(jtracker_url)s
"""

