## $Id: export.py 12820 2015-03-24 08:52:53Z uli $
##
## Copyright (C) 2012 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
##
"""Exporters for payments.
"""
import grok
from waeup.ikoba.interfaces import ICSVExporter
from waeup.ikoba.interfaces import MessageFactory as _
from waeup.ikoba.utils.batching import ExporterBase
from waeup.ikoba.utils.helpers import iface_names
from waeup.ikoba.payments.interfaces import IPayment


class PaymentExporterBase(grok.GlobalUtility, ExporterBase):
    """Exporter for payments.

    This is a baseclass.
    """
    grok.baseclass()
    iface = None
    title = None

    @property
    def fields(self):
        return tuple(sorted(iface_names(self.iface, exclude_attribs=False)))

    def mangle_value(self, value, name, context=None):
        """Hook for mangling values in derived classes
        """
        if name == 'payment_items' and value is not None:
            value = [eval(entry.to_string()) for entry in value]
        return super(PaymentExporterBase, self).mangle_value(
            value, name, context)

    def export(self, payments, filepath=None):
        """Export `payments`, an iterable, as CSV file.

        If `filepath` is ``None``, a raw string with CSV data is returned.
        """
        writer, outfile = self.get_csv_writer(filepath)
        for payment in payments:
            self.write_item(payment, writer)
        return self.close_outfile(filepath, outfile)

    def export_all(self, site, filepath=None):
        """Export payments in paymentscontainer into filepath as CSV data.

        If `filepath` is ``None``, a raw string with CSV data is returned.
        """
        payments = site.get('payments', {})
        return self.export(payments.values(), filepath)


class PaymentExporter(PaymentExporterBase):
    """Exporter for payments.

    """
    grok.implements(ICSVExporter)
    grok.name('payments')
    iface = IPayment
    title = _(u'Payments')
