# Path: zipfelchappe/payment_provider.py
# class BasePaymentProvider(object):
#     """
#     The abstract base class for all payment providers.
#     """
#     def __init__(self, name):
#         self.name = name
# 
#     def __unicode__(self):
#         return 'Base payment provider'
# 
#     def payment_url(self):
#         """
#         :return: The payment URL
#         """
#         raise NotImplementedError()
# 
#     # TODO: use this instead of global urls.
#     def get_provider_url_patterns(self):
#         """
#         Return the local url patterns
#         :return: A list of url instances
#         """
#         raise NotImplementedError
# 
#     def validate_project(self, project, db_instance=None):
#         """
#         A provider can validate a project.
#         :param project: The project instance to validate
#         :param db_instance: The project instance in the database
#         :raise: ValidationError
#         """
#         pass
# 
#     def collect_pledge(self, pledge):
#         """
#         Collects payment for the given pledge.
#         :param pledge: An authorized pledge.
#         """
#         raise NotImplementedError()
# 
#     def refund_pledge(self, pledge):
#         """
#         Frees reserved funds for the given pledge.
#         :param pledge: An authorized pledge.
#         """
#         raise NotImplementedError()
# 
#     def collect_billable_payments(self, project):
#         """
#         Collects billable payments for the given project.
#         :param project: The project to collect payments for.
#         :return: The amount of processed pledges.
#         """
#         pledges = project.authorized_pledges.filter(provider=self.name)
#         for pledge in pledges:
#             try:
#                 self.collect_pledge(pledge)
#             except PaymentProviderException as e:
#                 logger.info(e.message)
# 
#     def refund_payments(self, project):
#         """
#         Refunds reserved payments for the given project.
#         :param project: The project to collect payments for.
#         :return: The amount of processed pledges.
#         """
#         raise NotImplementedError()
# 
# Path: zipfelchappe/paypal/tasks.py
# def process_pledge(pledge):
#     """ 
#     Collect the paypal payment of one pledge
#     
#     Payments are asynchronous and we'll get notified about payment status by 
#     paypal via IPN Messages.
#     """
#     
#     try:
#         preapproval = pledge.paypal_preapproval
#     except Preapproval.DoesNotExist:
#         raise PaypalException('No preapproval for this pledge found')
# 
#     # All seems ok, try to execute paypal payment
#     pp_payment = create_payment(preapproval)
#     pp_data = pp_payment.json()
# 
#     Payment.objects.create(
#         key=pp_data.get('payKey', 'ERROR_%s' % preapproval.key[:14]),
#         preapproval=preapproval,
#         status=pp_data.get('paymentExecStatus', 'ERROR'),
#         data=json.dumps(pp_data, indent=2),
#     )
# 
#     if pp_data and 'error' in pp_data:
#         # Mark pledge as FAILED after 3 retries
#         if preapproval.payments.count() >= 3:
#             pledge.status = Pledge.FAILED
#             pledge.save()
#         for error in pp_data['error']:
#             raise PaypalException(error['message'])
#     
#     return pp_data
# 
# Path: zipfelchappe/paypal/app_settings.py
# MAXIMUM_ALLOWED_REWARD = 100  # US$


from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from ..payment_provider import BasePaymentProvider
from .tasks import process_pledge
from .app_settings import MAXIMUM_ALLOWED_REWARD
# coding: utf-8
from __future__ import absolute_import, unicode_literals


class PaypalProvider(BasePaymentProvider):
    """
    The Payment Provider Postfinance.
    """
    def __unicode__(self):
        return 'Paypal'

    def payment_url(self):
        return reverse('zipfelchappe_paypal_payment')

    def collect_pledge(self, pledge):
        return process_pledge(pledge)

    def validate_project(self, project, db_instance=None):
        """
        A provider can validate a project.
        :param project: The project instance to validate
        :param db_instance: The project instance in the database
        :raise: ValidationError
        """
        rewards = project.rewards.all()
        if len(rewards) > 0:
            for reward in rewards:
                if reward.minimum > MAXIMUM_ALLOWED_REWARD:
                    raise ValidationError(_('A reward cannot exceed the amount of US$ %(amount)s. '
                                            'Please consult the PayPal Crowdfunding Application '

# Path: zipfelchappe/payment_provider.py
# class BasePaymentProvider(object):
#     """
#     The abstract base class for all payment providers.
#     """
#     def __init__(self, name):
#         self.name = name
# 
#     def __unicode__(self):
#         return 'Base payment provider'
# 
#     def payment_url(self):
#         """
#         :return: The payment URL
#         """
#         raise NotImplementedError()
# 
#     # TODO: use this instead of global urls.
#     def get_provider_url_patterns(self):
#         """
#         Return the local url patterns
#         :return: A list of url instances
#         """
#         raise NotImplementedError
# 
#     def validate_project(self, project, db_instance=None):
#         """
#         A provider can validate a project.
#         :param project: The project instance to validate
#         :param db_instance: The project instance in the database
#         :raise: ValidationError
#         """
#         pass
# 
#     def collect_pledge(self, pledge):
#         """
#         Collects payment for the given pledge.
#         :param pledge: An authorized pledge.
#         """
#         raise NotImplementedError()
# 
#     def refund_pledge(self, pledge):
#         """
#         Frees reserved funds for the given pledge.
#         :param pledge: An authorized pledge.
#         """
#         raise NotImplementedError()
# 
#     def collect_billable_payments(self, project):
#         """
#         Collects billable payments for the given project.
#         :param project: The project to collect payments for.
#         :return: The amount of processed pledges.
#         """
#         pledges = project.authorized_pledges.filter(provider=self.name)
#         for pledge in pledges:
#             try:
#                 self.collect_pledge(pledge)
#             except PaymentProviderException as e:
#                 logger.info(e.message)
# 
#     def refund_payments(self, project):
#         """
#         Refunds reserved payments for the given project.
#         :param project: The project to collect payments for.
#         :return: The amount of processed pledges.
#         """
#         raise NotImplementedError()
# 
# Path: zipfelchappe/paypal/tasks.py
# def process_pledge(pledge):
#     """ 
#     Collect the paypal payment of one pledge
#     
#     Payments are asynchronous and we'll get notified about payment status by 
#     paypal via IPN Messages.
#     """
#     
#     try:
#         preapproval = pledge.paypal_preapproval
#     except Preapproval.DoesNotExist:
#         raise PaypalException('No preapproval for this pledge found')
# 
#     # All seems ok, try to execute paypal payment
#     pp_payment = create_payment(preapproval)
#     pp_data = pp_payment.json()
# 
#     Payment.objects.create(
#         key=pp_data.get('payKey', 'ERROR_%s' % preapproval.key[:14]),
#         preapproval=preapproval,
#         status=pp_data.get('paymentExecStatus', 'ERROR'),
#         data=json.dumps(pp_data, indent=2),
#     )
# 
#     if pp_data and 'error' in pp_data:
#         # Mark pledge as FAILED after 3 retries
#         if preapproval.payments.count() >= 3:
#             pledge.status = Pledge.FAILED
#             pledge.save()
#         for error in pp_data['error']:
#             raise PaypalException(error['message'])
#     
#     return pp_data
# 
# Path: zipfelchappe/paypal/app_settings.py
# MAXIMUM_ALLOWED_REWARD = 100  # US$


# Path: zipfelchappe/paypal/provider.py
from django.core.exceptions import ValidationError
from django.core.urlresolvers import reverse
from django.utils.translation import ugettext_lazy as _
from ..payment_provider import BasePaymentProvider
from .tasks import process_pledge
from .app_settings import MAXIMUM_ALLOWED_REWARD

# coding: utf-8
from __future__ import absolute_import, unicode_literals


class PaypalProvider(BasePaymentProvider):
    """
    The Payment Provider Postfinance.
    """
    def __unicode__(self):
        return 'Paypal'

    def payment_url(self):
        return reverse('zipfelchappe_paypal_payment')

    def collect_pledge(self, pledge):
        return process_pledge(pledge)

    def validate_project(self, project, db_instance=None):
        """
        A provider can validate a project.
        :param project: The project instance to validate
        :param db_instance: The project instance in the database
        :raise: ValidationError
        """
        rewards = project.rewards.all()
        if len(rewards) > 0:
            for reward in rewards:
                if reward.minimum > MAXIMUM_ALLOWED_REWARD:
                    raise ValidationError(_('A reward cannot exceed the amount of US$ %(amount)s. '
                                            'Please consult the PayPal Crowdfunding Application '

                                            'Guidelines.' % {'amount': MAXIMUM_ALLOWED_REWARD}))