# (C) Copyright 2004 Nuxeo SARL <http://nuxeo.com>
# Author: Georges Racinet <gracinet@nuxeo.com>
# Patched by Joachim Schmitz <js@aixtraware.de>
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
# 02111-1307, USA.
#
# $Id: utils.py 35055 2006-04-10 15:51:21Z gracinet $

from zLOG import LOG, DEBUG, TRACE
from copy import deepcopy
from AccessControl import ClassSecurityInfo
from Products.CPSSchemas.StorageAdapter import AttributeStorageAdapter
from Products.CPSDirectory.utils import QueryMatcher
security = ClassSecurityInfo()


security.declarePrivate('_searchEntries')
def _searchEntries(self, return_fields=None, **kw):
    """Search for entries in the directory.
    """
    if self.ZCacheable_isCachingEnabled():
        keyset = {'return_fields' : return_fields}
        keyset.update(kw)
        LOG('ZODBDirectory._searchEntries', TRACE,
            "Searching cache for %s" % (keyset,))
        from_cache = self.ZCacheable_get(keywords=keyset)
        if from_cache is not None:
            LOG('ZODBDirectory._searchEntries', TRACE, " -> results=%s" %
                (from_cache[:20],))
            return deepcopy(from_cache)
    else:
        keyset = None

    matcher = QueryMatcher(kw, accepted_keys=self._getFieldIds(),
                           substring_keys=self.search_substring_fields)

    # Compute needed fields from object.
    # All fields we need to return.
    field_ids_d, return_fields = self._getSearchFields(return_fields)
    # Add all fields the search is made on.
    field_ids = matcher.getKeysSet().union(field_ids_d)

    # Do the search.
    schema = self._getUniqueSchema()
    adapter = AttributeStorageAdapter(schema, None,
                                      field_ids=list(field_ids))
    res = []
    for id, ob in self.objectItems():
        if getattr(ob,'homeless',False):
            continue
        adapter.setContextObject(ob)
        entry = adapter.getData()
        adapter.finalizeDefaults(entry)
        if not matcher.match(entry):
            continue
        # Compute result to return.
        if return_fields is None:
            res.append(id)
        else:
            d = {}
            for key in return_fields:
                d[key] = entry[key]
            res.append((id, d))

    if keyset is not None:
        LOG('ZODBDirectory._searchEntries', TRACE, "Putting in cache")
        self.ZCacheable_set(res, keywords=keyset)

    return deepcopy(res)
from Products.CPSDirectory.ZODBDirectory import  ZODBDirectory
ZODBDirectory._searchEntries = _searchEntries
