## $Id: catalog.py 12824 2015-03-24 11:51:08Z uli $
##
## Copyright (C) 2011 Uli Fouquet & Henrik Bettermann
## This program is free software; you can redistribute it and/or modify
## it under the terms of the GNU General Public License as published by
## the Free Software Foundation; either version 2 of the License, or
## (at your option) any later version.
##
## 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
##
"""Components to help cataloging and searching payments.
"""
import grok
from zope.catalog.interfaces import ICatalog
from zope.component import queryUtility
from waeup.ikoba.interfaces import ICompany
from waeup.ikoba.payments.interfaces import IPayment


def search(query=None, searchtype=None):
    """Search payments catalog.

    `query` gives a string we search for, `searchtype` the fieldname.

    Query '*' returns all entries stored.

    Fields containing strings are searched in a
    'startswith'-manner. That means, we find all entries starting with
    the given query string.

    For other fields we only return exact matches. For instance for
    `anount`, we require a decimal number (no string) and will find
    all payments with that very amount given in `query`.

    Returns a (possibly empty) catalog result set.
    """
    # Temporary solution to display all payments added
    cat = queryUtility(ICatalog, name='payments_catalog')
    if query == '*':
        searchtype, query, upper_bound = 'payment_id', None, None
    else:
        if searchtype.endswith('_id'):
            upper_bound = query + ('Z' * 48)
        else:
            upper_bound = query
    search_params = {searchtype: (query, upper_bound)}
    results = cat.searchResults(**search_params)
    return results


class PaymentIndexes(grok.Indexes):
    """A catalog for all payments.
    """
    grok.site(ICompany)
    grok.name('payments_catalog')
    grok.context(IPayment)

    payment_id = grok.index.Field(attribute='payment_id')
    payer_id = grok.index.Field(attribute='payer_id')
    payable_id = grok.index.Field(attribute='payable_id')
    state = grok.index.Field(attribute='state')
    amount = grok.index.Field(attribute='amount')
