## $Id: vocabularies.py 12127 2014-12-03 18:09:28Z henrik $
##
## Copyright (C) 2014 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
##
"""Vocabularies and sources for the customer section.
"""
import grok
from zope.component import getUtility, queryUtility
from zope.catalog.interfaces import ICatalog
from zope.interface import implements, directlyProvides
from zope.schema.interfaces import ISource, IContextSourceBinder
from zope.schema.interfaces import ValidationError
from zc.sourcefactory.basic import BasicSourceFactory
from zc.sourcefactory.contextual import BasicContextualSourceFactory
from waeup.ikoba.sourcefactory import SmartBasicContextualSourceFactory
from waeup.ikoba.interfaces import SimpleIkobaVocabulary, SUBMITTED, VERIFIED
from waeup.ikoba.interfaces import MessageFactory as _
from waeup.ikoba.utils.helpers import get_sorted_preferred
from waeup.ikoba.utils.countries import COUNTRIES

#: a tuple of tuples (<COUNTRY-NAME>, <ISO-CODE>) with Nigeria first.
COUNTRIES = get_sorted_preferred(COUNTRIES, ['NG'])
nats_vocab = SimpleIkobaVocabulary(*COUNTRIES)


class GenderSource(BasicSourceFactory):
    """A gender source delivers basically a mapping
       ``{'m': 'Male', 'f': 'Female'}``

       Using a source, we make sure that the tokens (which are
       stored/expected for instance from CSV files) are something one
       can expect and not cryptic IntIDs.
    """
    def getValues(self):
        return ['m', 'f']

    def getToken(self, value):
        return value[0].lower()

    def getTitle(self, value):
        if value == 'm':
            return _('male')
        if value == 'f':
            return _('female')


class RegNumNotInSource(ValidationError):
    """Registration number exists already
    """
    # The docstring of ValidationErrors is used as error description
    # by zope.formlib.
    pass


class RegNumberSource(object):
    """A source that accepts any entry for a certain field if not used
    already.

    Using this kind of source means a way of setting an invariant.

    We accept a value iff:
    - the value cannot be found in catalog or
    - the value can be found as part of some item but the bound item
      is the context object itself.
    """
    implements(ISource)
    cat_name = 'customers_catalog'
    field_name = 'reg_number'
    validation_error = RegNumNotInSource
    comp_field = 'customer_id'

    def __init__(self, context):
        self.context = context
        return

    def __contains__(self, value):
        """We accept all values not already given to other customers.
        """
        cat = queryUtility(ICatalog, self.cat_name)
        if cat is None:
            return True
        kw = {self.field_name: (value, value)}
        results = cat.searchResults(**kw)
        for entry in results:
            if not hasattr(self.context, self.comp_field):
                # we have no context with comp_field (most probably
                # while adding a new object, where the container is
                # the context) which means that the value was given
                # already to another object (as _something_ was found in
                # the catalog with that value). Fail on first round.
                raise self.validation_error(value)
            if getattr(entry, self.comp_field) != getattr(
                self.context, self.comp_field):
                # An entry already given to another customer is not in our
                # range of acceptable values.
                raise self.validation_error(value)
                #return False
        return True


def contextual_reg_num_source(context):
    source = RegNumberSource(context)
    return source

directlyProvides(contextual_reg_num_source, IContextSourceBinder)


class ConCatProductSource(BasicContextualSourceFactory):
    """A contract category product source delivers all products
    which belong to a certain contract_category.
    """

    def getValues(self, context):
        concat = getattr(context, 'contract_category', None)
        products = grok.getSite()['products'].values()
        if not concat:
            return products
        resultlist = [
            value for value in products if value.contract_category == concat]
        return resultlist

    def getToken(self, context, value):
        return value.product_id

    def getTitle(self, context, value):
        return "%s - %s" % (value.product_id, value.title)


class CustomerDocumentSource(BasicContextualSourceFactory):
    """A customer document source delivers all submitted and verified documents
    of the context customer.
    """

    def getValues(self, context):
        # When checking conversion during import, contracts do not belong to
        # customers. Thus all portal documents must be returned.
        user_id = getattr(getattr(context, 'customer', None), 'user_id', None)
        catalog = getUtility(ICatalog, name='documents_catalog')
        results = catalog.searchResults(user_id=(user_id, user_id))
        resultlist = [
            value for value in results if value.state in (SUBMITTED, VERIFIED)]
        return resultlist

    def getToken(self, context, value):
        return value.document_id

    def getTitle(self, context, value):
        return "%s - %s" % (value.document_id, value.title)