## $Id$
##
## Copyright (C) 2022 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
##
# Classes that represent entitites needed when dealing with paypal.
import datetime
import grok
from zope.component import queryUtility
from kofacustom.nigeria.paypal.interfaces import IPaypalConfig


def module_activated(session, payment):
    #if payment is not None and not payment.p_currency in ('USD',):
    #    return False
    if queryUtility(IPaypalConfig) is None:
        return False
    if getattr(payment, 'r_company', '') and payment.r_company != 'paypal':
        return False
    config = grok.getSite()['configuration']
    session_conf = config.get(str(session)) or config.get(str(
        datetime.datetime.now().year))
    return getattr(session_conf, "paypal_enabled", False)


class Amount(object):
    """Paypal Amount

    A structure that represents amounts of money.
    """

    def __init__(self, value="0.00", currency_code="USD"):
        if type(value) in (int, float):
            value = "%.2f" % round(value, 2)
        self.value = value
        self.currency_code = currency_code

    def json(self):
        return dict(value=self.value, currency_code=self.currency_code)


class PurchaseUnit(object):
    """Paypal purchase unit.

    When creating paypal orders, the single things to be paid are passed
    formatted as `purchase units`.
    """

    def __init__(self, description="", amount=Amount(), custom_id=None):
        self.description = description
        self.amount = amount
        self.custom_id = custom_id

    def json(self):
        result = dict(
            amount=self.amount.json(),
            description=self.description,
        )
        if self.custom_id is not None:
            result["custom_id"] = self.custom_id
        return result
