from django.core.management import BaseCommand
from stripe_payment.models import StripeSource, StripeCustomer
import crayons
import stripe
from progressbar import ProgressBar
from stripe.error import InvalidRequestError


class Command(BaseCommand):
    help = 'Remove the cards that are not active in stripe from the database'

    def handle(self, *args, **options):
        sources = StripeSource.objects.filter(card__isnull=True).all()
        stripe.api_key = "sk_live_AowiYW0fdm78T79wQbibAiak"

        print(crayons.red('Deleting all non active cards'))
        for source in sources:
            source.delete()

        print(crayons.red('Done'))
        print(crayons.red('Checking for customers with not cards'))

        customers = set()
        for customer in StripeCustomer.objects.filter(sources__isnull=True):
            customers.add(customer.stripe_customer)

        print('=============================================================================')
        print(crayons.red('Cross check the below users with stripe'))
        print(customers)
        print('=============================================================================')

        print(crayons.red('Copying their details from stripe'))
        progress = ProgressBar(max_value=StripeCustomer.objects.filter(sources__isnull=True).count())
        count = 0

        # Try to update the customer with data from stripe.
        for customer in StripeCustomer.objects.filter(sources__isnull=True):
            try:
                stripe_customer = stripe.Customer.retrieve(customer.stripe_customer)
                for item in stripe_customer['sources']['data']:
                    if StripeSource.objects.filter(card_fingerprint=item['fingerprint'], customer=customer).exists():
                        continue
                    StripeSource.objects.create(
                        customer=customer,
                        card_fingerprint=item['fingerprint'],
                        card=item['id'],
                        card_brand=item['brand'],
                        expiry_month=item['exp_month'],
                        expiry_year=item['exp_year'],
                        last_digits=item['last4'],
                    )
                count += 1
                progress.update(count)
            except InvalidRequestError:
                count += 1
                continue
