import stripe
from stripe_payment.models import StripeSource
from django.core.management import BaseCommand
from django.db import transaction
from django.conf import settings
from pprint import pprint
import crayons
from progressbar import ProgressBar


class Command(BaseCommand):
    help = 'Get the missing data from the stripe api and update'

    def handle(self, *args, **options):
        stripe.api_key = "sk_live_AowiYW0fdm78T79wQbibAiak"
        total = StripeSource.objects.count()
        finished = 0
        qs = StripeSource.objects.prefetch_related('customer')
        problems = set()
        progress = ProgressBar(max_value=total)
        for source in qs.all():
            finished += 1
            progress.update(finished)
            # Since there is a chance of API errors and retries.
            if source.card:
                continue
            if not source.customer.stripe_customer:
                problems.add(source)
                continue
            with transaction.atomic():
                stripe_customer = stripe.Customer.retrieve(source.customer.stripe_customer)
                for item in stripe_customer['sources']['data']:
                    if item['fingerprint'] == source.card_fingerprint:
                        source.card = item['id']
                        source.card_brand = item['brand']
                        source.expiry_month = item['exp_month']
                        source.expiry_year = item['exp_year']
                        source.last_digits = item['last4']
                        source.save()
        print('Done!')
        print(crayons.red(problems))
