# Copyright (c) 2002-2009 Infrae. All rights reserved.
# See also LICENSE.txt
# Zope 3
from zope.interface import implements
# Five
from Products.Five import BrowserView
# SilvaLayout
from Products.SilvaLayout import interfaces
from DateTime import DateTime

_catalogName = 'service_catalog'
class CatalogQueryView(BrowserView):
    def parseDateString(self, dateString):
        """
        """
        return DateTime(dateString)

    def createDateQuery(self, indexName, start=None, end=None,
        sort_order=None):
        """Creates a query dict usable for date queries
        """
        dateQuery = {}
        dateQuery['query'] = []
        dateQuery['sort_on'] = indexName
        dateQuery['sort_order'] = sort_order
        if start is not None:
            dateQuery['range'] = 'min'
            dateQuery['query'].append(start)
        if end is not None:
            dateQuery['range'] = 'max'
            dateQuery['query'].append(end)
        if len(dateQuery['query']) == 2:
            dateQuery['range'] = 'minmax'
        query = {indexName:dateQuery} 
        if sort_order is not None:
            query['sort_on'] = indexName
            query['sort_order'] = sort_order

        return query

    def execute(self, query):
        """Execute a query (using a ZCatalog query). Returns a list of catalog
        brains
        """
        context = self.context.aq_inner
        return getattr(context.get_root(), _catalogName)(query)

class SimpleCatalogQueryView(CatalogQueryView):

    def executeQuery(self, index, value):
        """Execute a query. 

           For Silva, the following indices are currently available:

           fulltext (ZCTextIndex)
           haunted_path FieldIndex
           id FieldIndex
           meta_type FieldIndex
           path (indexed attributes: getPhysicalPath) PathIndex
           silva-extraexpirationtime ProxyIndex
           silva-extrapublicationtime ProxyIndex
           silvamaintitle ProxyIndex
           silvashorttitle ProxyIndex
           version_status FieldIndex

           This method returns the brain objects of the catalog,
           on which the following metadata fields are available:

           id
           silva_object_url
           meta_type

           More metadata fields can be added to service_catalog using the ZMI,
           but a catalog reindexing step is needed to make the field values
           available.
           """
        query = {index: value}
        context = self.context.aq_inner
        return self.execute(query) 
