from django.core.management.base import BaseCommand
from django.contrib.contenttypes.models import ContentType
from django.db import transaction
from hookmigration.models import Transient
from hookmigration.peewee_models import CustomersCustomer, LoyalePoint
from django.contrib.auth.models import User
from oscar.core.loading import get_model
import crayons
from progressbar import ProgressBar
from loyalty.models import Point


class Command(BaseCommand):
    help = 'Migrate the users points'

    def handle(self, *args, **options):
        point_records = LoyalePoint.select()

        total = point_records.count()
        finished = 0
        progress = ProgressBar(max_value=total)

        user_content_type = ContentType.objects.get_for_model(User)
        point_content_type = ContentType.objects.get_for_model(Point)

        missing = set()

        with transaction.atomic():
            for record in point_records:
                new_user_transient = Transient.objects.filter(content_type=user_content_type).filter(
                    old_pk=record.user_id).first()
                if not new_user_transient:
                    missing.add(record.user_id)
                    continue
                user = User.objects.get(pk=new_user_transient.new_pk)

                # Add the point
                point = Point.objects.create(
                    user=user,
                    points=record.points,
                    created=record.added
                )

                # Add the transient
                Transient.objects.create(
                    old_pk=record.id,
                    new_pk=point.pk,
                    content_type=point_content_type,
                    old_model=LoyalePoint.__class__.__name__
                )

                finished += 1
                progress.update(finished)
        print('All Done')
