from __future__ import unicode_literals

from django import forms
import stripe

from ..forms import PaymentForm as BasePaymentForm
from .widgets import StripeWidget
from . import RedirectNeeded


class PaymentForm(BasePaymentForm):

    charge = None

    def __init__(self, *args, **kwargs):
        super(PaymentForm, self).__init__(*args, **kwargs)
        widget = StripeWidget(provider=self.provider, payment=self.payment)
        self.fields['stripeToken'] = forms.CharField(widget=widget)
        if self.is_bound and not self.data.get('stripeToken'):
            self.payment.change_status('rejected')
            raise RedirectNeeded(self.payment.get_failure_url())

    def clean(self):
        data = self.cleaned_data

        if not self.errors and not self.payment.transaction_id:
            stripe.api_key = self.provider.secret_key
            try:
                self.charge = stripe.Charge.create(
                    capture=False,
                    amount=int(self.payment.total * 100),
                    currency=self.payment.currency,
                    card=data['stripeToken'],
                    description='%s %s' % (
                        self.payment.billing_last_name,
                        self.payment.billing_first_name))
            except stripe.CardError as e:
                # The card has been declined
                self._errors['__all__'] = self.error_class([e])
                self.payment.change_status('error', e.message)

        return data

    def save(self):
        self.charge.capture()
        self.payment.transaction_id = self.charge.id
        self.payment.captured_amount = self.payment.total
        self.payment.change_status('confirmed')

@@ -59,16 +59,67 @@
 t forms%0A
+from django.utils.translation import ugettext as _%0A
 import s
@@ -802,20 +802,32 @@
 f.errors
- and
+:%0A            if
  not sel
@@ -852,16 +852,20 @@
 ion_id:%0A
+    
         
@@ -922,16 +922,20 @@
         
+    
 try:%0A   
@@ -939,32 +939,36 @@
                 
+   
+ 
 self.charge = st
@@ -1007,16 +1007,20 @@
         
+    
 capture=
@@ -1046,16 +1046,20 @@
         
+  
+  
 amount=i
@@ -1108,16 +1108,20 @@
         
+    
 currency
@@ -1164,16 +1164,20 @@
         
+ 
+   
 card=dat
@@ -1194,16 +1194,20 @@
 oken'%5D,%0A
+    
         
@@ -1258,32 +1258,36 @@
                 
+    
 self.payment.bil
@@ -1318,32 +1318,36 @@
                 
+   
+ 
 self.payment.bil
@@ -1376,16 +1376,20 @@
         
+    
 except s
@@ -1426,16 +1426,20 @@
         
+  
+  
 # The ca
@@ -1459,16 +1459,20 @@
 eclined%0A
+    
         
@@ -1535,32 +1535,36 @@
                 
+ 
+   
 self.payment.cha
@@ -1593,16 +1593,168 @@
 message)
+%0A            else:%0A                msg = _('This payment has already been processed.')%0A                self._errors%5B'__all__'%5D = self.error_class(%5Bmsg%5D)
 %0A%0A      

Return error on a repeated Stripe's payment