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


class Command(BaseCommand):
    help = 'Find stripe users without stripe card fingerprint in the database'

    def handle(self, *args, **options):
        customers = StripeCustomer.objects.filter(sources__isnull=True).distinct().all()
        stripe.api_key = settings.STRIPE_SECRET_KEY

        progress = ProgressBar(max_value=customers.count())
        done = 0
        issues = []

        for customer in customers:
            try:
                cards = stripe.Customer.list_sources(customer.stripe_customer, object='card')
            except Exception as e:
                issues.append({
                    'customer': customer.pk,
                    'error': str(e)
                })
                continue
            for card in cards:
                StripeSource.objects.create(
                    customer=customer,
                    card=card['id'],
                    card_brand=card['brand'],
                    expiry_month=card['exp_month'],
                    expiry_year=card['exp_year'],
                    last_digits=card['last4'],
                )
            done += 1
            progress.update(done)
        print('----------------------------------------------------------------------------------')
        pprint(issues)
        print('----------------------------------------------------------------------------------')
