from django.core.management.base import BaseCommand
from django.contrib.contenttypes.models import ContentType
from hookmigration.models import Transient
from hookmigration.peewee_models import CustomersCustomer, CustomersCardfingerprint
from django.contrib.auth.models import User
from stripe_payment.models import StripeSource, StripeCustomer
from django.db import transaction
import crayons
from pprint import pprint


class Command(BaseCommand):
    help = 'Migrate all the stripe customer IDS'

    def handle(self, *args, **options):
        user_content_type = ContentType.objects.get_for_model(User)
        stripe_source_content_type = ContentType.objects.get_for_model(StripeSource)
        total = CustomersCustomer.select().count()
        finished = 0
        missing = []
        double_entry = []

        with transaction.atomic():
            for customer in CustomersCustomer.select():
                new_user_id = Transient.objects.filter(content_type=user_content_type).filter(
                    old_pk=customer.user_id).first()
                if not new_user_id:
                    missing.append(customer)
                    continue
                new_user = User.objects.get(pk=new_user_id.new_pk)

                # Create the stripe customer
                stripe_customer = StripeCustomer(
                    user=new_user,
                    stripe_customer=customer.stripe_id
                )
                stripe_customer.save()
                # Create the cards
                count = 0
                for item in customer.fingerprints:
                    stripe_source = StripeSource(
                        customer=stripe_customer,
                        card_fingerprint=item.fingerprint,
                        default=True if count == 0 else False
                    )
                    stripe_source.save()
                    count += 1
                    Transient.objects.create(content_type=stripe_source_content_type,
                                             old_pk=item.id,
                                             new_pk=stripe_source.pk)
                finished += 1
                print('Finished {}/{}'.format(crayons.red(finished), crayons.blue(total)))
        print('The below were missing')
        print('===========================================================================')
        pprint(missing)
        print('===========================================================================')
        print('The below are double entry cards')
        pprint(double_entry)
        print('===========================================================================')
